mongoose:删除子文档的内容

我有一个Mongoose(使用当前版本)模式与子文档:

var mySchema = new Schema({ subdocument: { property1: { type: String } } }); var myModel = mongoose.model('My-Model', mySchema); 

现在我正在尝试更新现有文档,并像使用doc.subdocument = {}一样删除subdocument

 new myModel({ name: 'test', subdocument: { property1: 'test' }}).save(function(err, doc) { console.log('saved doc:\n', doc); doc.subdocument = {}; // remove content of subdocument doc.save(function(err, doc) { console.log('updated doc:\n', doc); // subdocument: null myModel.findById(doc._id, function(err, doc) { console.log('retrieved doc:\n', doc); // subdocument: { property1: 'test' } mongoose.disconnect(); }); }); }); 

doc.save的callback返回文档的subdocument: null ,所以我认为,更新按预期工作。 但是,在检查数据库时, subdocument的内容仍然存在 – 当我再次检索文档时,可以通过上面的示例代码看到。

数据库中的文件看起来像:

 { subdocument: { property1: 'test' }, __v: 0, _id: 57593a8130f2f7b6a12886b1 } 

这是一个错误还是根本的误解?

我相信模式中的常规JS对象属性被Mongoose赋予了一个Mixed模式types。

对于这些types的属性,如果它们发生变化,则需要在保存之前明确告诉Mongoose该更改:

 doc.subdocument = {}; doc.markModified('subdocument'); doc.save(...); 

“更新的文档” 不会反映文档存储在数据库中,只是它在内存中的表示方式(它只是对doc对象的另一个引用)。

作为.save()的替代方法,您还可以使用findByIdAndUpdate() ,并增加一个优点,即可以使用new选项返回已更新(存储在数据库中)的文档:

 myModel.findByIdAndUpdate(doc._id, { $set : { subdocument : {} } }, { new : true }, function(err, doc) { // `doc` will now reflect what's stored in the database });