Home > Blockchain >  mongoose schema findone and update array subdocument
mongoose schema findone and update array subdocument

Time:04-20

This is my mongoose schema:

userId is a unique number generated by Okta for user profiles. '''

var book_listSchema = new mongoose.Schema({

userId:{type: String, required: true},
first_name: { type: String, required: true},
last_name:{ type: String, required: true},
newList: [{

         list_name: String,
         books:
    [{
        book_name: {type: String, required: true},
        book_author: {type: String, required: true},
        date_added: {type: Date, default: Date.now},
        date_finished: {type: Date, default: Date.now},

    }]}],


    });

'''
   

This is the code I'm using to find and update, adding a book to the books array.

 '''
 book_list.findOneAndUpdate({"userId": req.userContext.userinfo.sub, newList:{"newList.list_name": list_name}}, {$push:{books:{book_name: title, book_author:author, date_added: new Date()}}}

 '''

The books array does not get updated and each object in newList has the list_name, and there are different lists each with their own books array, so the correct list needs to be updated when a book is added.

Sample data set:

  '''
            _id:625c81d7622b044fb297ce54

             userId:"00uvgyn7OikAwud6"
             first_name:"John"
             last_name:"Smith"
             newList:Array
                 0:Object
                   list_name:"read"
                   books:Array
                      0:Object
                      book_name:"The Great Gatsby"
                      book_author:"Francis Scott Fitzgerald"
                      date_added:2022-04-19T00:43:24.248 00:00
                     _id:625e05ac083663dc44f37804
                    date_finished:2022-04-19T00:43:24.252 00:00
                    _id:625e05ac083663dc44f37803
                    __v:0
  '''

CodePudding user response:

The right way is:

db.collection.update({
  userId: "00uvgyn7OikAwud6",
  newList: {
    $elemMatch: {
      list_name: "read"
    }
  }
},
{
  $push: {
    "newList.$.books": {
      book_name: "a new book",
      book_author: "some author",
      date_added: new Date()
    }
  }
})

or in your code way

db.collection.update({
  userId: req.userContext.userinfo.sub,
  newList: {
    $elemMatch: {
      list_name: list_name
    }
  }
},
{
  $push: {
    "newList.$.books": {
      book_name: title,
      book_author: author,
      date_added: new Date()
    }
  }
})

$elemMatch allows you to match more than one component within the same array element and then you can use $push to add the specific object in the array.

You can run it here to check the same query https://mongoplayground.net/p/YnzDRfhwpEt

You can also have a look at documentation of $elemMatch in this link.

Let me know if you face any issue.

  • Related