[英]Check if a key in array of objects in Javascript?
我嘗試檢查一個值是否在數組的對象中。 之后我推送 object 是值不在數組中。 我怎樣才能做到這一點?
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()
}
})
我的 mongoose model:
const User = new Schema({
firstName: {
type: String,
required: true
},
favorites: [{
_id: Object,
idSave: String
}]
});
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;
}
);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.