mongodb NodeJs Mongoose -从文档的数组中删除一个ID

quhf5bfb  于 2023-01-12  发布在  Go
关注(0)|答案(1)|浏览(160)

我的模型文档中有一个数组。我想删除该数组中的一个id。可以吗?

我试过了。

module.exports.RemoveFavourite = async (req, res, next) => {
  try {
    const userId = req.params.user;
    const favouriteId = req.params.event;

    const removeFavourite = await User.updateOne(
      { _id: userId },
      { $pull: { favourites: favouriteId } }
    );

    res.status(200).json(removeFavourite);
  } catch {
    res.status('404').json('error');
  }
};
rdrgkggo

rdrgkggo1#

转换收藏夹Id string to ObjectId

const mongoose = require("mongoose")

module.exports.RemoveFavourite = async (req, res, next) => {
  try {
    const userId = req.params.user;
    const favouriteId = req.params.event;

    const removeFavourite = await User.updateOne(
      { _id: userId },
      { $pull: { favourites: mongoose.Type.ObjectId(favouriteId) } }
    );

    res.status(200).json(removeFavourite);
  } catch {
    res.status('404').json('error');
  }
};

相关问题