0
我想要做的事情应该是直截了当的,但由于某种原因,我很难理解这一点。我有以下Mongoose模式(简化)。如何使用Mongoose将嵌入式文档从一个文档放入另一个文档?
var Status = new Schema({
name : { type: String, required: true },
description : { type: String }
});
var Category = new Schema({
statuses : [Status], // contains a list of all available statuses
// some other attributes
});
var Book = new Schema({
statuses : [Status], // preferably this would not be an array but a single document, but Mongoose doesn't seem to support that
// some other attributes
});
现在,我要做到以下几点:
- 检索类别文档
- 查找特定的嵌入式状态文件(根据要求PARAM)
- 分配一个特定的嵌入式状态文件到一个特定的书籍文件。我想要替换现有的图书状态,因为在任何时候,应该只有一本书的状态。
这是目前我在做什么:
mongoose.model('Category').findOne({_id: id}, function(err, category){
if(err) next(err);
var status = category.statuses.id(statusId); // statusId available via closure
book.statuses[0] = status; // book available via closure; trying to replace the existing status here.
book.save(function(err){
if(err) next(err);
next();
});
});
上面看上去一切正常,我没有得到任何错误。但是,新状态不会保存到文档中。下次我输出更新的Book文档时,它仍然具有旧的状态。我调试了这个和find()方法以及设置状态似乎没有问题。
我现在唯一能想到的是,我分配的状态值不是以正确的格式保存在Mongoose中。尽管如此,我仍然期待某种错误消息。
或者也许有更好的方法来做到这一切吗?