【问题标题】:$pull is not working for array in mongoose (MongoDB)$pull 不适用于猫鼬(MongoDB)中的数组
【发布时间】:2021-01-22 00:56:34
【问题描述】:

在 mongoDB(通过 mongoose)中,我试图删除集合数组中的一个元素并为此使用 $pull 运算符,但它不起作用。

mongoDB 中的房间集合

{
"_id":"sampleObjectId",
"users": ["email1@example.com", "email2@example.com"]
}

删除用户的后端代码(使用 Node.js 的猫鼬)

Rooms.update(
              { _id: "sampleRoomId" },
              {
                $pull: {
                    users: "email1@exmple.com" }
                },
              }
            )

注意在运行此代码时发生了收集,没有发生任何变化。代码运行没有错误,并在输出中显示 "nModified":0 。 我不知道如何从集合中删除用户。

【问题讨论】:

  • mongoplayground.net/p/f58HFvHkJcC 这按您的预期工作
  • 您的更新文档中有错字,email1@exmple.com 而不是email1@example.com
  • @varman 请查看此代码link,它不起作用
  • 感谢您的指点,但是。我刚刚给出了我的真实代码示例(给出的代码不是真实的),错字不是真正的问题@MontgomeryWatts。请查看此link
  • _id 是一个 ObjectId 但您将值作为字符串传递。将其转换为 ObjectId,例如 so

标签: node.js mongodb express mongoose web-development-server


【解决方案1】:
//actual code output from the mongo shell. This is working as expected. check if you given //correct value in object_id query parameter.

> db.rooms.find();
{ "_id" : "sampleObjectId", "users" : [ "email1@example.com", "email2@example.com" ] }
> db.rooms.update(
... {_id: "sampleObjectId"},
... {$pull:{users:"email1@example.com"}}
... );
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.rooms.find();
{ "_id" : "sampleObjectId", "users" : [ "email2@example.com" ] }
> db.version();
4.2.6
>

【讨论】:

    猜你喜欢
    • 2013-06-24
    • 2021-11-08
    • 1970-01-01
    • 2017-12-19
    • 2021-06-18
    • 2021-03-12
    • 2016-04-11
    • 2019-06-21
    • 2020-05-19
    相关资源
    最近更新 更多