34

I have the following mongoose schema:

user = {
    "userId" : "myId",
    "connections":
    [{
        "dateConnectedUnix": 1334567891,
        "isActive": true
    }, {
        "dateConnectedUnix": 1334567893,
        "isActive": false
    }]
}

I would like to delete the second item in the connections array, to get the following:

user = {
    "userId" : "myId",
    "connections": 
    [{
        "dateConnectedUnix": 1334567893,
        "isActive": false
    }]
}

The following code does the job as expected:

userAccounts.update(
    { 'connections.isActive': false }, 
    { $pull: { 'connections.isActive':false }}, 
    function (err, val) {
        console.log(val)
    }
);

But, I need to delete based on ObjectId. And the following goes does not work:

userAccounts.update(
    { 'connections._id': '1234-someId-6789' }, 
    { $pull: { 'connections._id': '1234-someId-6789' } },
    function (err, val) {
        console.log(val)
    }
);

Any suggestions? I have been banging my head against the screen (aka Google, Stackoverflow, ...) for hours and have had no luck.

4

7 回答 7

49

上面的代码似乎不起作用。它甚至不应该适用于我给出的第一个例子。

最后我在这里得到了这个答案的支持:MongoDB, remove object from array

这是我的工作代码:

userAccounts.update( 
    { userId: usr.userId },
    {
        $pull: {
            connections: { _id : connId }
        }
    },
    { safe: true },
    function removeConnectionsCB(err, obj) {
        // ...
    }
);
于 2013-11-28T22:11:13.967 回答
17

我有一个像

在此处输入图像描述

我必须从地址数组中删除地址

在互联网上搜索了很多后,我找到了解决方案

Customer.findOneAndUpdate(query, {$pull: {address: addressId}}, (err, data) => {
    if (err) {
        return res.status(500).json({ error: 'error in deleting address' });
    }
    res.json(data);   
});
于 2015-07-23T09:07:27.303 回答
10
user: {
 _id: ObjectId('5ccf3fa47a8f8b12b0dce204'),
 name: 'Test',
 posts: [
  ObjectId("5cd07ee05c08f51af8d23b64"),
  ObjectId("5cd07ee05c08f51af8d23c52")
 ]
}

从帖子数组中删除单个帖子

user.posts.pull("5cd07ee05c08f51af8d23b64"); user.save();

于 2019-05-06T20:16:49.677 回答
8

要将更新与 ObjectId 一起使用,您应该使用 ObjectId 对象而不是字符串表示:

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)
    }
);
于 2013-11-05T10:13:56.890 回答
4

用于findByIdAndUpdate从数组中删除项目

你可以在mongoose 5.4.x and above

const result = await User.findByIdAndUpdate(user_id, {
    $pull: {
        someArrayName: { _id: array_item_id }
    }
}, { new: true });

if (result)
    console.log(result)

数组中的项目将根据提供的属性_id值被删除

于 2019-02-08T12:18:57.413 回答
1

在猫鼬 5.8.11 中,这$pull: { ... }对我不起作用,到目前为止还不确定为什么。所以我以这种方式在我的控制器中克服了它:

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) {
    // ...
  }
};
于 2020-02-11T10:14:04.213 回答
1

猫鼬:4.11.11
对我有用的是以下语法:

const removeTansactionFromUser = (userId, connectionId) => {
    return User.findByIdAndUpdate(userId, { $pull: { "connections": connectionId} }, {'new': true} );
};

Mongoose 支持字符串格式或 ObjectId 格式的 id。
提示:new ObjectId(stringId)从字符串切换到 ObjectId

于 2017-09-23T07:17:35.523 回答