1

I'm trying to update and object inside array in MongoDB. my model is:

let userSchema = new mongoose.Schema({
  userName: {
    type: String
  },
  password: {
    type: String
  },
  history: []

});

And inside history each element is from the next type: id, array(named ing_array) and boolean field called favorite.

I'm trying to update the favorite field with mongoose with the userName and the id.

I tried to do this query and I didn't succed.
Could some one tell me whats worng? [object photo]: https://i.sstatic.net/2mYpP.png

User.findOneAndUpdate(
  { "userName": user_name, "history.id": id },
  { "$set": { "history.$.favorite": true }}
);

1 Answer 1

3

You have to use arrayFilters in this way:

db.collection.update({
  "userName": "uname",
  "history.id": 1
},
{
  "$set": {
    "history.$[element].favorite": false
  }
},
{
  "arrayFilters": [
    {
      "element.id": 1
    }
  ]
})

Note that update query has the format: update(query, update, options) (Check the docs).

When you do { "userName": user_name, "history.id": id } you are telling mongo "Give me all documents where userName is user_name and array history has an id with value id. This return all history array because it belows to the document.

To update an specific object into the array is neccessary to use arrayFilters to tell mongo which object do you want to update. In this case the object where id is equal to 1. You can use as you want to match wit your requirements.

Example here

Sign up to request clarification or add additional context in comments.

6 Comments

first of all thank you, i need to put the name of the mongoose model instead the db.collection right? if i med let User= mongoose.mode('User,...) so i need to do User.update?
Yes! You have to use your mongoose model User.updateOne(/*the query*/).
its not working for me..i see that in the example its working.. do you can suggest what is the problem?
What's the problem? Is not updating the field? Check if first object (query object) is finding some document using yourModel.find({ "userName": user_name, "history.id": id }). If this works the query should works. Also note that where I've used "element.id": 1 you have to use "element.id": id
i think that the problem is in the history array. i dont think that i can do history.id becuse history is an array so i think this is the problem.. do you have any clue?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.