【发布时间】:2012-02-15 20:59:09
【问题描述】:
在a official mongoose site 中,我发现了如何通过数组中的 _id 删除嵌入的文档:
post.comments.id(my_id).remove();
post.save(function (err) {
// embedded comment with id `my_id` removed!
});
我有兴趣如何更新而不是删除这个?
【问题讨论】:
在a official mongoose site 中,我发现了如何通过数组中的 _id 删除嵌入的文档:
post.comments.id(my_id).remove();
post.save(function (err) {
// embedded comment with id `my_id` removed!
});
我有兴趣如何更新而不是删除这个?
【问题讨论】:
应该是这样的:
YOURSCHEMA.update(
{ _id: "DocumentObjectid" , "ArrayName.id":"ArrayElementId" },
{ $set:{ "ArrayName.$.TheParameter":"newValue" } },
{ upsert: true },
function(err){
}
);
在此示例中,我正在搜索带有 id 参数的元素,但它可能是 objectId 类型的实际 _id 参数。
【讨论】:
你可以的
var comment = post.comments.id(my_id);
comment.author = 'Bruce Wayne';
post.save(function (err) {
// emmbeded comment with author updated
});
【讨论】:
更新到有关在 Mongoose 中处理子文档的最新文档。 http://mongoosejs.com/docs/subdocs.html
var Parent = mongoose.model('Parent');
var parent = new Parent;
// create a comment
parent.children.push({ name: 'Liesl' });
var subdoc = parent.children[0];
console.log(subdoc) // { _id: '501d86090d371bab2c0341c5', name: 'Liesl' }
subdoc.isNew; // true
parent.save(function (err) {
if (err) return handleError(err)
console.log('Success!');
});
【讨论】: