Search code examples
javascriptmongodbmlab

How to insert a new item to mLab array according to a specific id


I use mLab for my database. I have a collection of lists where each list has an object with _id, userId and an array of items.

Now I want to add a new item to the array of a specific list.

The function that connects to Mongo has the new item object and the list id.

How do I find the correct list and add the new item to items array?

the JSON of each list looks like this:

{
    "_id": {
        "$oid": "5ded5eb7e7179a3015b0672f"
    },
    "userID": "1234",
    "items": [
        {
            "_id": "abc12345",
            "name": "abc",
        },
        {
            "_id": "abc12346",
            "name": "def",
        }
    ]
}

and the function that connects to Mongo looks like this:

function addItem({item, listId}) {
    return MongoService.connect()
    .then(db => {
        const collection = db.collection('lists');
        //need to do something here
    })
}

connect to Mongo : (which works fine, I do connect and load the lists)

function connectToMongo() {
    if (dbConn) return Promise.resolve(dbConn);
    const MongoClient = require('mongodb').MongoClient;
    const url = 'mongodb:// ***my user and password ***';
    return MongoClient.connect(url)
        .then(client => {
            console.log('Connected to MongoDB');
            client.on('close', ()=>{
                console.log('MongoDB Diconnected!');
                dbConn = null;
            })
            dbConn = client.db()
            return dbConn;
        })
}
module.exports = {
    connect : connectToMongo
}

Solution

  • I see you are using the MongoDB node native driver. Documentation exists on how to update a MongoDB document with the driver here.

    In order to add an item to list.items array, this is what the addItem function should look like:

    function addItem({ item, listId }) {
      return MongoService.connect()
        .then(db => {
          const collection = db.collection('lists');
          // The update query below would return a promise
          return collection.updateOne({
            { _id: new ObjectID(listId) }
          }, { '$push': { items: item } })
        })
        .then(result => { // Anything you want to do with the result })
    }