i have following schemas:
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 })
when add image add new image doc find logged in user , update favorites so:
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) }); }); }
when remove favorite delete image , update user reference image. code looks this:
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) }) }) }
when test out, image deleted, user reference in favorites never updates reflect changes. going wrong here?
there no _id
access prime favourites, instead:
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 array of objectid not object _ids { $pull: { favorites: id } }, { new: true }, function(err, removedfromuser) { if (err) { console.error(err) } res.status(200).send(removedfromuser) }) }) }