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

142 views Asked by At

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.

1

There are 1 answers

0
turivishal On BEST ANSWER

You have to do 2 separate queries,

  • Find user document
  • Check condition if books field present
  • If Present then push object, else set new field
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,

  • $ifNull check is field is null then return []
  • $concatArrays to concat current books with new book object
var bookData = { id: 'book1', title: 'this is book1' };
db.collection('userData').update({
    // put your condition
  },
  [{
    $set: {
      books: {
        $concatArrays: [
          { $ifNull: ["$books", []] },
          [bookData]
        ]
      }
    }
  }],
  { multi: true }
);

Playground