Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UpdateOne returns a mongoose object and not document

Tags:

mongoose

When running this query:

  const project = await models.Projects
    .updateOne(
      { _id: projectId },
      {
        $addToSet:
        {
          membersIds:
          {
            $each: membersIds
          },
        },
      },
    );

The response I get is the follwoing:

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

Is it possible to get an updated object instead of this mongoose data?

like image 721
Le garcon Avatar asked Mar 01 '19 12:03

Le garcon


People also ask

What does UpdateOne return in mongoose?

UpdateOne returns a mongoose object and not document.

What is the difference between UpdateOne and findOneAndUpdate?

findOneAndUpdate returns a document whereas updateOne does not (it just returns the _id if it has created a new document).

What is Upsert in mongoose?

May 20, 2019. In MongoDB, an upsert means an update that inserts a new document if no document matches the filter . To upsert a document in Mongoose, you should set the upsert option to the Model.

What is new true in MongoDB?

If new is true : the modified document if the query returns a match; the inserted document if upsert: true and no document matches the query; otherwise, null .


2 Answers

From the docs: [callback] «Function» params are (error, writeOpResult) which means that there's no way to return a document with updateOne method.

Instead of updateOne it's however possible to use findByIdAndUpdate providing lean: true option

like image 191
Le garcon Avatar answered Sep 21 '22 14:09

Le garcon


ATTENTION !

I saw the responses, they are all right, BUT, pay attention to add the new option and to set it as true into the query to get the new updated document, otherwise it will return back the document before updating:

    models.Projects.findByIdAndUpdate(
    { "_id": projectId }, 
    { $addToSet:{ membersIds: { $each: membersIds }}})
   .exec()
   .then((response) => {
          console.log('document before updating =>', response);
        });

    models.Projects.findByIdAndUpdate(
        { "_id": projectId }, 
        { $addToSet:{ membersIds: { $each: membersIds }}}, 
        {new: true})
       .exec()
       .then((response) => {
              console.log('document after updating =>', response);
            });
like image 38
Ahmad MOUSSA Avatar answered Sep 18 '22 14:09

Ahmad MOUSSA