简体   繁体   English

MongoDB mongoose 更新 elemMatch 不起作用但查询(查找)时没问题

[英]MongoDB mongoose update elemMatch doesn't work but when query (find) it's ok

I'm having some problems on update using $elemMatch.我在使用 $elemMatch 进行更新时遇到了一些问题。 When I try to match or find, it shows the write result.当我尝试匹配或查找时,它会显示写入结果。

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

It's resulting:结果是:

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

And it's the query result using find:这是使用 find 的查询结果:

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

Sample doc result of find:查找的示例文档结果:

[
  {
    _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
  }
]

can anybody help me?有谁能够帮我? Thank you!!谢谢!!

You can try like below:您可以尝试如下:

If your documents look something like:如果您的文件如下所示:

/* 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
}

So $elemMatch is not needed on single query condition which in your case {comments: { $elemMatch: { fid: '5ea9c87d2d5c8f491cae8818' } }} can just be "comments.fid": "5ea9c87d2d5c8f491cae8818" , also you don't need $and operator in your .find() .因此,在您的情况下,单个查询条件不需要$elemMatch {comments: { $elemMatch: { fid: '5ea9c87d2d5c8f491cae8818' } }}可以只是"comments.fid": "5ea9c87d2d5c8f491cae8818" ,你也不需要$and .find()中的运算符。

Query:询问:

  /** 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);
  });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM