Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update and/or add array element properties using req.body via Mongoose?

I have the following document:

{
    "_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")
        }
    ]
}

Now in an incoming form via req.body, I have 2 fields: title and description.

I want to update title and insert description for a specified pdf_id, how do I do that?

So in the end, my document will now look like:

{
    "_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")
        }
    ]
}

Just to be clear, I'm really just looking for the Mongoose update syntax.

like image 736
k00k Avatar asked Sep 11 '12 16:09

k00k


1 Answers

You can use the $ positional operator to refer to the matched pdfs array element in your $set:

Model.update(
    { 'pdfs.pdf_id': pdf_id }, 
    { $set: { 
        'pdfs.$.title': title, 
        'pdfs.$.description': description 
    }}, function (err, numAffected) { ... }
);
like image 119
JohnnyHK Avatar answered Nov 01 '22 03:11

JohnnyHK