5

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.

k00k
  • 17,314
  • 13
  • 59
  • 86

1 Answers1

9

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) { ... }
);
JohnnyHK
  • 305,182
  • 66
  • 621
  • 471
  • 1
    In the `$set`, is there any way to assign those properties dynamically? The user may not supply some, and I'd prefer to not have to specify them explicitly. – k00k Sep 11 '12 at 17:37
  • Sure, you'd just need to build up that `$set` object programmatically and then pass that object in as the second parameter to the `update` call. Sort of like in this other question: http://stackoverflow.com/questions/12184626/nodejs-mongo-insert-into-subdocument-dynamic-fieldname/12185214#12185214 – JohnnyHK Sep 11 '12 at 17:41
  • Cool, thanks. Something that tripped me up, that might help others: It wouldn't update for me when I just had my array set to mixed `[]`. I had to built out the schema for the array and make sure that the _id of the array element you're trying to update is specified as a `type: Schema.Types.ObjectId` in your schema. – k00k Sep 11 '12 at 17:53