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
    }]
});
lf_celine
  • 653
  • 7
  • 19

1 Answers1

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;
  }
);
varun249
  • 1,436
  • 2
  • 11
  • 9
  • I have a `Tried to set nested object field `favorites` to array `[object Object]` and strict mode is set to throw.` with your solution – lf_celine Jul 30 '20 at 07:14