使用req.body通过Mongoose更新和/或添加数组元素属性?

k00*_*00k 5 mongoose mongodb node.js express

我有以下文件:

{
    "_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")
        }
    ]
}
Run Code Online (Sandbox Code Playgroud)

现在在传入的表单中req.body,我有2个字段:titledescription.

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

所以最后,我的文档现在看起来像:

{
    "_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")
        }
    ]
}
Run Code Online (Sandbox Code Playgroud)

为了清楚起见,我真的只是在寻找Mongoose update语法.

Joh*_*yHK 9

您可以使用$位置运算符来引用您的匹配pdfs数组元素$set:

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