node.jsmongodbmongodb-nodejs-driver

mongodb, check if the key exist while appending to an array


Note: checking if the key books exist or not, creating if not and than updating it.

I am using mongodb driver with nodejs.

In the db.collection('userData')The document looks like this:

{ 
    user_id: 'user1',
    books: [{
               id: 'book1',
               title: 'this is book1'
    },
            {
               id: 'book1',
               title: 'this is book1'
    }]
}

when inserting a new book entry, how to check if the array of books exists in the document, if not then add a key books in the document and then insert the book entry.


Solution

  • You have to do 2 separate queries,

    var user_id = "user1";
    var bookData = { id: 'book1', title: 'this is book1' };
    
    // FIND USER DATA
    var userData = await db.collection('userData').findOne({ user_id: user_id }, { books: 1 });
    
    var updateBody = { $push: { books: bookData } };
    // IF BOOKS FIELD NOT PRESENT THEN SET NEW
    if (!userData.books) {
      updateBody = { $set: { books: [bookData] } };
    }
    
    var updateData = await db.collection('userData').updateOne({ user_id: user_id }, updateBody);
    
    console.log(updateData);
    

    Second option you can use update with aggregation pipeline starting from MongoDB 4.2,

    var bookData = { id: 'book1', title: 'this is book1' };
    db.collection('userData').update({
        // put your condition
      },
      [{
        $set: {
          books: {
            $concatArrays: [
              { $ifNull: ["$books", []] },
              [bookData]
            ]
          }
        }
      }],
      { multi: true }
    );
    

    Playground