简体   繁体   中英

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

I'm having some problems on update using $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({
        $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() .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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