0

I try to check if a value is in array's objects. After that I push the object is the value is not in the array. How can I do this ?

router.post('/save', (req, res) => {
let userId = req.user.id
let dataPushSave = req.body.idSave
let dataPushSaveObj = {idSave: dataPushSave}

User.findById(userId, (err, user) => {
    if (user.favorites.idSave !== dataPushSave) {
        user.favorites.push(dataPushSaveObj)
        user.save()
    }
})

My mongoose model:

    const User = new Schema({
    firstName: {
        type: String,
        required: true
    },
    favorites: [{
        _id: Object,
        idSave: String
    }]
});
1
  • like this? Commented Jul 29, 2020 at 12:21

1 Answer 1

1
    const User = new Schema({
    firstName: {
        type: String,
        required: true
    },
    favorites: [{
        _id: Object,
        idSave: String
    }]
});

From the above schema, remove _id: Object from favorites. I would recommend below schema

const User = new Schema({
    firstName: {
        type: String,
        required: true
    },
    favorites: {
        type: [new Schema({
        idSave: { type: String },
      }, { _id: false })]
    }
});

Then use $addToSet operator to make sure there are no duplicates in the favorites array.

let user;
User.findByIdAndUpdate(
  userId, 
  { $addToSet: {  favorites: dataPushSaveObj } }, 
  { new: true }, // this option will make sure you get the new updated docc
  (err, doc) => {
    if (err) console.error(err);
    user = doc;
  }
);
Sign up to request clarification or add additional context in comments.

1 Comment

I have a Tried to set nested object field favorites` to array [object Object] and strict mode is set to throw.` with your solution

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.