Node.js Mongoose – 从文档中的数组中移除一个ID

huangapple go评论72阅读模式
英文:

NodeJs Mongoose - remove one id from array in document

问题

我有一个在我的模型文档中的数组。我想要移除其中一个id。这是可能的吗?

英文:

I have an array in my model document. I would like to remove one id in that array. Is this possible?

Node.js Mongoose – 从文档中的数组中移除一个ID

This is what I tried.

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

答案1

得分: 1

favouriteId从字符串转换为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.Types.ObjectId(favouriteId) } }
    );

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

convert favouriteId string to ObjectId

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const mongoose = require("mongoose")

module.exports.RemoveFavourite = async (req, res, next) =&gt; {
  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(&#39;404&#39;).json(&#39;error&#39;);
  }
};

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年1月9日 17:50:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/75055524.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定