英文:
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?
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) => {
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');
}
};
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论