【问题标题】:mongodb pull object from an array not working using mongoosemongodb从数组中提取对象不使用猫鼬
【发布时间】:2019-06-21 05:34:18
【问题描述】:

我正在尝试使用 $pull 运算符从 mongodb 中的数组中删除评论对象,看起来我的语法正确,但它没有修改任何内容。

我已经查看了 Stack 上给出的所有示例,但它仍然不断响应

{ n: 0,
nModified: 0,
opTime:
{ ts:
  Timestamp { _bsontype: 'Timestamp', low_: 1, high_: 1548664023 },
 t: 1 },
electionId: 7fffffff0000000000000001,
ok: 1,
operationTime:
 Timestamp { _bsontype: 'Timestamp', low_: 1, high_: 1548664023 },
'$clusterTime':
 { clusterTime:
  Timestamp { _bsontype: 'Timestamp', low_: 1, high_: 1548664023 },
  signature: { hash: [Binary], keyId: [Long] } } }

这是我目前在数据库中的字段

 {
"_id" : ObjectId("5be23d8aa365d853ddfd6f15"),
"__v" : 0,
"restaurant" : {
    info about restaurant
},
"comments" : [
    {
        "id" : "61DSLu7fFcUZ2chA8-A6HQ",
        "user" : "test",
        "comment" : "test"
    },
    {
        "comment" : "testing",
        "user" : "testing",
        "id" : ObjectId("5c3cd3a5647f180484a5ca18")
    },
    {
        "restaurant_id" : "61DSLu7fFcUZ2chA8-A6HQ",
        "comment" : "tacos",
        "name" : "test",
        "user_id" : ObjectId("5c48fdf47e9ed81b08536602")
    },
    {
        "restaurant_id" : "61DSLu7fFcUZ2chA8-A6HQ",
        "comment" : "tacos",
        "name" : "test",
        "comm_id" : ObjectId("5c49019f8528f31b2adfb914")
    },
    {
        "restaurant_id" : "61DSLu7fFcUZ2chA8-A6HQ",
        "comment" : "hello",
        "name" : "test",
        "comm_id" : ObjectId("5c490237fd6e781b52f801fe")
    }
],
"likes" : {
    "likes" : 6
}

目前我的模型显示在我的餐厅模型中

comments: [{
    restaurant_id : String,
    comment : String,
    name : String,
    comm_id : String,
  }]

我目前的更新方式

db.restaurants.updateOne({restaurant_id: rest_id},
    { $pull: { comments: { $in: [{comment: "hello"}] } }
  }, { safe: true })

也尝试过

db.restaurants.updateOne({restaurant_id: rest_id},
    { $pull: { comments: { $in: {"comment": "hello"} } }
  }, { safe: true })

还有

db.restaurants.updateOne({restaurant_id: rest_id},
    { $pull: { comments: { comment: "hello"} } }
 }, { safe: true })

和类似的变体。我似乎无法确定我的错误。响应似乎是在找到正确的餐厅字段,但我的 $pull 操作员无法正常工作。我的语法有问题还是在这种情况下不起作用。

理想情况下,我将使用 comm_id 字段从数组中删除对象,但我使用注释:“hello”只是为了测试。

可能是因为我在前几个 cmets 中的字段不同?

【问题讨论】:

    标签: javascript arrays mongodb object mongoose


    【解决方案1】:

    简单点就行了

    db.restaurants.updateOne({restaurant_id: rest_id},
        { $pull: { comments.comment: "hello"}  }
     }, { safe: true })
    

    【讨论】:

    • 似乎给了我一个新错误 "index" : 0, "code" : 28, "errmsg" : "Cannot use the part (comment) of (cmets.comment) to traverse the element
    • 当我从 mongoshell 运行 restaurant.updateOne({ restaurant_id: 'rest_id' }, { '$pull': { cmets: { comment: 'hello' } } }, { safe: true }) ,它似乎工作,但是当我从邮递员运行时,它似乎不起作用
    • 我发现了我的问题,是使用已部署的 mongodb 与我正在测试的 localone。你的答案对我有用。所以接受它作为答案。
    猜你喜欢
    • 2021-05-13
    • 2022-09-27
    • 2022-07-20
    • 2017-07-05
    • 2017-03-28
    • 2018-07-12
    • 2015-12-28
    • 2021-05-06
    • 2012-11-01
    相关资源
    最近更新 更多