Node.js 嵌入式文档的Mongoose更新
我在尝试理解如何在mongoose中更新嵌入文档的值时,慢慢变得疯狂,并编写了一些node.js代码来演示这个问题Node.js 嵌入式文档的Mongoose更新,node.js,mongodb,mongoose,Node.js,Mongodb,Mongoose,我在尝试理解如何在mongoose中更新嵌入文档的值时,慢慢变得疯狂,并编写了一些node.js代码来演示这个问题 var mongoose = require('mongoose'); var Schema = mongoose.Schema; mongoose.connect('mongodb://localhost/mongoose_broken'); var ASchema = new Schema({ value : { type: String, index: { uni
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)");
}
});
}
});
});
});
运行此命令的输出为:
b looks like it was updated (first check)
b was not updated! (second check)
知道为什么不保存嵌入文档的更新吗?在父模式中使用子模式之前,必须先声明子模式
var BSchema = new Schema({
value : { type: String },
});
var ASchema = new Schema({
value : { type: String, index: { unique: true } },
bs : [BSchema],
});
如果您执行
console.log(doc_2.bs)代码>doc_2console.log(doc_2.bs)打印“[[Object Object]]”,console.log(doc_2.bs[0])给出“{value:'world',_id:4f8ee35f82228240f4300002}”,你知道了-这就解决了它。我认为这是一个bug,因为如果你引用了一个不存在的模式,你会得到一个错误,但当它们出现故障时就不会了。。。真出乎意料!不管怎样,我今晚可以睡个好觉,知道这已经解决了-谢谢亚伦:)这是一个叫做“提升”的东西