I have the following mongoose schema:
user = {
\"userId\" : \"myId\",
\"connections\":
[{
\"dateConnectedUnix\": 1334567891,
\"is
user: {
_id: ObjectId('5ccf3fa47a8f8b12b0dce204'),
name: 'Test',
posts: [
ObjectId("5cd07ee05c08f51af8d23b64"),
ObjectId("5cd07ee05c08f51af8d23c52")
]
}
Remove a single post from posts array
user.posts.pull("5cd07ee05c08f51af8d23b64");
user.save();
mongoose: 4.11.11
What have worked for me is the following syntax:
const removeTansactionFromUser = (userId, connectionId) => {
return User.findByIdAndUpdate(userId, { $pull: { "connections": connectionId} }, {'new': true} );
};
Mongoose support id in string format or ObjectId format.
Tip: new ObjectId(stringId)
to switch from string to ObjectId
I have a document like
I have to delete address from address array
After searching lots on internet I found the solution
Customer.findOneAndUpdate(query, {$pull: {address: addressId}}, function(err, data){
if(err) {
return res.status(500).json({'error' : 'error in deleting address'});
}
res.json(data);
});
It seems that the above code would not work. It should not even have worked for the first example I gave.
In the end I was supported by this answer here: MongoDB, remove object from array
Here is my working code:
userAccounts.update(
{ userId: usr.userId },
{ $pull: { connections : { _id : connId } } },
{ safe: true },
function removeConnectionsCB(err, obj) {
...
});
In mongoose 5.8.11, this $pull: { ... }
didn't work for me, so far not sure why. So I overcame it in my controller this way:
exports.removePost = async (req, res, next) => {
const postId = req.params.postId;
try {
const foundPost = await Post.findById(postId);
const foundUser = await User.findById(req.userId);
if (!foundPost || !foundUser) {
const err = new Error(
'Could not find post / user.',
);
err.statusCode = 404;
throw err;
}
// delete post from posts collection:
await Post.findByIdAndRemove(postId);
// also delete that post from posts array of id's in user's collection:
foundUser.posts.pull({ _id: postId });
await foundUser.save();
res.status(200).json({ message: 'Deleted post.' });
} catch (err) {
// ...
}
};
To use update with ObjectId, you should use ObjectId object instead of string representation :
var ObjectId = require('mongoose').Types.ObjectId;
userAccounts.update({'connections._id': new ObjectId('1234-someId-6789') },
{$pull: { 'connections._id': new ObjectId('1234-someId-6789') }},
function (err,val) {
console.log(val)
});