I'm slowly going mad trying to understand how to update the value of an embedded document in mongoose, and written some node.js code which demonstrates the problem.
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
mongoose.connect('mongodb://localhost/mongoose_broken');
var ASchema = new Schema({
value : { type: String, index: { unique: true } },
bs : [BSchema],
});
var BSchema = new Schema({
value : { type: String },
});
var A = mongoose.model('A', ASchema);
var B = mongoose.model('B', BSchema);
// Add an entry of A, with 1 embedded B
//
var a = new A();
a.value = "hello";
var b = new B();
b.value = "world";
a.bs.push(b);
a.save(function(err) {
if (err) {
console.log("Error occured during first save() " + err);
return;
}
// Now update a by changing a value inside the embedded b
//
A.findOne({ value: 'hello' }, function(err, doc) {
if (err) { console.log("Error occured during find() " + err); return; }
doc.bs[0].value = "moon";
doc.save(function(err) {
if (err) console.log("Error occuring during second save()");
// Check b was updated?
//
if (doc.bs[0].value != "moon") {
console.log ("b was not updated! (first check)");
} else {
console.log ("b looks like it was updated (first check)");
// Do a fresh find
//
A.findOne({value: "hello"}, function(err, doc_2) {
if (err) { console.log("Error occured during second find() " + err); return; }
if (doc_2.bs[0].value != "moon") {
console.log ("b was not updated! (second check)");
} else {
console.log ("b looks like it was updated (second check)");
}
});
}
});
});
});
Output from running this is:
b looks like it was updated (first check)
b was not updated! (second check)
Any idea why the update of the embedded document is not saved?
You must declare child schemas before using them in parents.
var BSchema = new Schema({
value : { type: String },
});
var ASchema = new Schema({
value : { type: String, index: { unique: true } },
bs : [BSchema],
});