仅当 mongodb 中的数组中不存在 ObjectID 时,如何使用猫鼬添加 ObjectId?

How to add ObjectId only if the ObjectID is not present in the array in mongodb using mongoose?

所以我有一个模式,我想在其中将 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 不在 favoriteSellers 数组中时。我也可以在发送卖家 ID 之前在前端执行逻辑,但不确定在后端执行而不是在前端担心是否会更好。谢谢!

查看 Mongoose docs for adding subdocs to arrays,我认为您应该可以使用 addToSet 而不是 push:

result.favoriteSellers.push(seller_id);

变成

result.favoriteSellers.addToSet(seller_id);