我有以下架构:
const userSchema = new Schema({
email: {
type: String,
unique: true,
lowercase: true
},
password: String,
favorites: [{ type: Schema.Types.ObjectId, ref: 'image' }]
})
const imageSchema = new Schema({
description: String,
title: String,
url: String
})
当我添加图像时,我会添加一个新的图像文档,然后我找到登录的用户并像这样更新他的收藏夹:
exports.addImage = function(req, res, next) {
const email = req.user.email;
imageData = req.body;
imageData.url = req.body.media.m;
const newImg = new Image(imageData);
newImg.save()
.then(function(image) {
User.findOneAndUpdate(
{ email: email },
{ $push: { favorites: image._id } },
function(err, doc) {
if (err) { console.error(err) }
res.status(201).send(doc)
});
});
}
当我删除收藏夹时,我想删除图像并更新用户对图像的引用。我的代码如下所示:
exports.deleteImageById = function(req, res, next) {
const email = req.user.email;
const id = req.body.id;
Image.findOneAndRemove({ _id: id })
.exec(function(err, removed) {
User.findOneAndUpdate(
{ email: email },
{ $pull: { favorites: { _id: id } } },
{ new: true },
function(err, removedFromUser) {
if (err) { console.error(err) }
res.status(200).send(removedFromUser)
})
})
}
当我测试它时,图像被删除了,但收藏夹中的用户引用永远不会更新以反射(reflect)更改。这里出了什么问题?
最佳答案
收藏夹中没有_id
访问素数,改为:
exports.deleteImageById = function(req, res, next) {
const email = req.user.email;
const id = req.body.id;
Image.findOneAndRemove({ _id: id })
.exec(function(err, removed) {
User.findOneAndUpdate(
{ email: email },
// no _id it is array of objectId not object with _ids
{ $pull: { favorites: id } },
{ new: true },
function(err, removedFromUser) {
if (err) { console.error(err) }
res.status(200).send(removedFromUser)
})
})
}
关于javascript - 如何删除 Mongoose 文档并从另一个模型引用它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37668623/