所以我有一個架構,我想將 ObjectID 添加到 mongoose 中的 id 陣列中,我嘗試添加它是唯一的,但沒有奏效。很可能是因為我需要迭代檢查,但不確定如何在 mongoose/mongodb 中進行檢查。有人能幫我嗎?
架構如下所示:
const favoriteSchema = new mongoose.Schema({
user: {
type: mongoose.Schema.Types.ObjectId,
ref: "User",
unique: true,
},
favoriteSellers: [
//create array of object id, make sure they are unique for user not to add multiple sellers
{
type: mongoose.Schema.Types.ObjectId,
ref: "Seller",
unique: true,
},
],
});
這是我嘗試僅在不存在時插入物件 ID 的代碼:
router.put("/favorite", async (req, res) => {
const seller_id = mongoose.Types.ObjectId(req.body.seller_id);
Favorite.findOne({ user: req.user._id })
.then(async function (result) {
if (!result) {
return res
.status(404)
.send({ error: "Could not find your list. Contact support team." });
}
result.favoriteSellers.push(seller_id);
await result.save();
res.send(result);
})
.catch((err) => {
res.status(404).send({ error: "Could not add to favorites" });
});
});
所以我正在做的是獲取用戶 id 并將新的賣家 id 添加到陣列中,但我想添加條件當且僅當賣家 id 在 favouriteSellers 陣列中不存在時。我也可以在發送賣家 ID 之前在前端做邏輯,但不確定是否最好只在后端做而不用在前端擔心。謝謝!
uj5u.com熱心網友回復:
查看用于將子檔案添加到陣列的 Mongoose 檔案,我認為您應該能夠使用addToSet而不是push:
result.favoriteSellers.push(seller_id);
變成
result.favoriteSellers.addToSet(seller_id);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/471283.html
上一篇:MongoDB中的哪個關系更好?
下一篇:MongoDB聚合然后展平
