Voice Of The Rain Voice Of The Rain - 11 days ago 6
Node.js Question

Add and update subdocument in mongoDB and node js (without mongoose)

I'm fairly new to node js and mongoDB and I need to add or update a Subdocument on mongodb collection as follow :

{
"_id": "58286e49769e3729e895d239",
"id": "2",
"title": "Session Title",
"sessiondate": "2016-02-11T21:00:00.000Z",
"startTime": "14:30",
"endTime": "16:30",
"breakStartTime": "16:30",
"breakEndTime": "18:00",
"talks": [
{
"id": "3",
"title": "Android",
"speaker": {
"id": "1",
"name": "john doe",
"about": "about the speaker",
"photo": "https://pbs.twimg.com/profile_images/566353055788978177/dUy_ueY2.jpeg"
}
}
]
}


All the solutions I have found is using mongoose, where in this specific project we decided not to use mongoose, any thoughts?

Answer

To add or update a new talk in the embedded document, you can use any of the atomic update operators depending on how many documents in the collection you want to update. For a single atomic update, use the updateOne() method as in the following example:

1. Adding a new subdocument

// Example of adding a subdocument to an existing document.

var MongoClient = require('mongodb').MongoClient,
    ObjectId = require('mongodb').ObjectId;

MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {

    // Get a collection
    var collection = db.collection('mycollection');

    // The new talk document to be added 
    var doc = {
        "id": "4",
        "title": "PyData",
        "speaker": {
            "id": "7",
            "name": "alice bob",
            "about": "about the speaker",
            "photo": "https://pbs.twimg.com/dUy_ueY2.jpeg"
        }
    };

    // Update the document with an atomic operator
    collection.updateOne(
        { "_id": ObjectId("58286e49769e3729e895d239") },
        { "$push": { "talks": doc } },
        function(err, result){
            console.log(result);
            db.close();
        }
    )

});

In the above, you use the $push operator to append the specified document to an array of embedded documents (talks field).


2. Updating an existing subdocument

// Example of updating an existing subdocument.

var MongoClient = require('mongodb').MongoClient,
    ObjectId = require('mongodb').ObjectId;

MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {

    // Get a collection
    var collection = db.collection('mycollection');

    // Update the document with an atomic operator
    collection.updateOne(
        { 
            "_id": ObjectId("58286e49769e3729e895d239"),
            "talk.id": "3"
        },
        { "$set": { 
            "talks.$.title": "Android version 7.0",
            "talks.$.speaker.name": "foo bar"
        } },
        function(err, result){
            console.log(result);
            db.close();
        }
    )

});

With an existing document update, you apply the $set operator together with the $ positional operator in your update operation to change the embedded document fields. The $ positional operator will identify the correct element in the array to update without explicitly specifying the position of the element in the array. For this to work, the array field must appear as part of the query document, hence the query

{ 
    "_id": ObjectId("58286e49769e3729e895d239"),
    "talk.id": "3" // <-- array field is part of the query
}
Comments