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.

1 Answer 1

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) { ... }
);
Sign up to request clarification or add additional context in comments.

3 Comments

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.
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: stackoverflow.com/questions/12184626/…
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.