我有以下文件:

{
    "_id" : ObjectId("503b83dfad79cc8d26000004"),
    "pdfs" : [
        {
            "title" : "Test document",
            "pdf_id" : ObjectId("504f6793ce351a595d000004"),
            "created_at" : ISODate("2012-09-11T16:32:19.276Z")
        },
        {
            "title" : "Some other doc",
            "pdf_id" : ObjectId("502bf124b4642341230003f0"),
            "created_at" : ISODate("2012-09-11T11:34:19.276Z")
        }
    ]
}

现在以req.body的形式传入,我有2个字段:titledescription

我想更新title并为指定的pdf_id插入description,我该怎么做?

因此,最后,我的文档将如下所示:
{
    "_id" : ObjectId("503b83dfad79cc8d26000004"),
    "pdfs" : [
        {
            "title" : "This is an UPDATED title",
            "description" : "It has an ALL NEW description",
            "pdf_id" : ObjectId("504f6793ce351a595d000004"),
            "created_at" : ISODate("2012-09-11T16:32:19.276Z")
        },
        {
            "title" : "Some other doc",
            "pdf_id" : ObjectId("502bf124b4642341230003f0"),
            "created_at" : ISODate("2012-09-11T11:34:19.276Z")
        }
    ]
}

需要明确的是,我实际上只是在寻找Mongoose update语法。

最佳答案

您可以使用 $ positional operatorpdfs中引用匹配的$set数组元素:

Model.update(
    { 'pdfs.pdf_id': pdf_id },
    { $set: {
        'pdfs.$.title': title,
        'pdfs.$.description': description
    }}, function (err, numAffected) { ... }
);

关于node.js - 通过Mongoose使用req.body更新和/或添加数组元素属性?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12374345/

10-09 20:07