问题描述
|
我想做的事情应该很简单,但是由于某种原因,我很难解决这个问题。我有以下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
});
现在,我要执行以下操作:
检索类别文档
查找特定的嵌入式状态文档(基于请求参数)
将该特定的嵌入式状态文档分配给特定的Book文档。我想替换现有的“图书”状态,因为在任何给定时间,一本书只能设置一个状态。
这是我目前正在做的事情:
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()方法以及设置状态似乎都很好。
我现在唯一能想到的就是我分配的状态值不正确地以猫鼬保存。虽然,我希望那时会出现某种错误消息。
还是有更好的方法来完成所有这些工作?
解决方法
这可能是因为您试图复制嵌入的文档,该文档本身可能具有与之关联的ObjectId。尝试将重复的“ 2”保存在“ 3”中会创建两个具有相同“ 4”的嵌入文档。尝试创建一个新的Status对象并复制字段。
很难找到5英镑的嵌入式文档文档,但此处提到了它们:http://mongoosejs.com/docs/embedded-documents.html。