【问题标题】:MongoDB mongoose update elemMatch doesn't work but when query (find) it's okMongoDB mongoose update elemMatch 不起作用,但查询(查找)时没问题
【发布时间】:2020-08-14 01:26:31
【问题描述】:

我在使用 $elemMatch 进行更新时遇到了一些问题。 当我尝试匹配或查找时,它会显示写入结果。

.updateOne(
        { _id: req.body.sid },
        { $pull: {comments: { $elemMatch: { fid: '5ea9c87d2d5c8f491cae8818' } }}}
     ).then((res)=>{
         console.log(res)
     }).catch((err)=>{
         console.log(err)
     })

结果:

{ n: 1, nModified: 0, ok: 1 }

这是使用 find 的查询结果:

.find({
        $and: [
            { _id: req.body.sid },
            {comments: { $elemMatch: { fid: '5ea9c87d2d5c8f491cae8818' } }}
        ]
    }) 

查找的示例文档结果:

[
  {
    _id: 5ea88b12423e6e4b3ce01956,
    comments: [{"fid":"5ea9c87d2d5c8f491cae8818","comment":"ok"}, {"fid":"5ea9c87d2d5c8f491cae8899","comment":"ok"}],
    date: 2020-04-28T00:00:00.000Z,
    title: 'Fotos para o Álbum de ensaios',
    __v: 5
  }
]

谁能帮帮我?谢谢!!

【问题讨论】:

  • 你的comments: [ [Array] ] 看起来像一个对象数组吗?
  • 它是一个对象数组:[{"fid":"5ea9c87d2d5c8f491cae8818","comment":"ok"}]

标签: node.js mongodb mongoose mongodb-query


【解决方案1】:

您可以尝试如下:

如果您的文档看起来像这样:

/* 1 */
{
    "_id" : "5ea88b12423e6e4b3ce01956",
    "comments" : [ 
        {
            "fid" : "5ea9c87d2d5c8f491cae8818"
        }, 
        {
            "fid" : "5ea9c87d2d5c8f491cae8899"
        }
    ],
    "date" : "2020-04-28T00:00:00.000Z",
    "title" : "Fotos para o Álbum de ensaios",
    "__v" : 5.0
}

/* 2 */
{
    "_id" : "5ea88b12423e6e4b3ce01951",
    "comments" : [ 
        {
            "fid" : "5ea9c87d2d5c8f491cae8811"
        }, 
        {
            "fid" : "5ea9c87d2d5c8f491cae8899"
        }
    ],
    "date" : "2020-04-28T00:00:00.000Z",
    "title" : "Fotos para o Álbum de ensaios",
    "__v" : 5.0
}

所以在单个查询条件下不需要$elemMatch,在你的情况下{comments: { $elemMatch: { fid: '5ea9c87d2d5c8f491cae8818' } }} 可以只是"comments.fid": "5ea9c87d2d5c8f491cae8818",你也不需要$and 运算符在你的.find() 中。

查询:

  /** Here "comments.fid" helps to filter doc, even though we'll get single doc based on `_id` filter but 
   * still adding this check prevents unnecessary update operation if `5ea9c87d2d5c8f491cae8818` doesn't exists in fid of comments in doc */

  .updateOne(
    { _id: req.body.sid, "comments.fid": "5ea9c87d2d5c8f491cae8818" }, 
    { $pull: { "comments" :{ "fid": "5ea9c87d2d5c8f491cae8818" } } }
  )
  .then((res) => {
    console.log(res);
  })
  .catch((err) => {
    console.log(err);
  });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-04-24
    • 2016-02-20
    • 2019-08-24
    • 1970-01-01
    • 1970-01-01
    • 2022-01-15
    • 1970-01-01
    相关资源
    最近更新 更多