Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/35.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
检查Javascript中的对象数组中是否有键?_Javascript_Mongoose - Fatal编程技术网

检查Javascript中的对象数组中是否有键?

检查Javascript中的对象数组中是否有键?,javascript,mongoose,Javascript,Mongoose,我尝试检查数组的对象中是否有值。之后,我推送对象的值不在数组中。我该怎么做 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.i

我尝试检查数组的对象中是否有值。之后,我推送对象的值不在数组中。我该怎么做

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()
    }
})
我的猫鼬模型:

    const User = new Schema({
    firstName: {
        type: String,
        required: true
    },
    favorites: [{
        _id: Object,
        idSave: String
    }]
});
从上面的模式中,从收藏夹中删除_id:Object。 我推荐以下模式

const User = new Schema({
    firstName: {
        type: String,
        required: true
    },
    favorites: {
        type: [new Schema({
        idSave: { type: String },
      }, { _id: false })]
    }
});
然后使用$addToSet运算符确保收藏夹数组中没有重复项

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;
  }
);

我有一个
尝试将嵌套对象字段
收藏夹`设置为数组
[object object]
,并将严格模式设置为throw。`使用您的解决方案
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;
  }
);