jmrueda
jmrueda

Reputation: 1428

Mongoose updateOne with parameter {new:true} not showing actual updated value

I am struggling for a couple of hours to show the final value of an updated document (via mongoose updateOne). I successfully modify it as I can see "nModified: 1" when I call the endpoint on Postman, but I am not able to output the actual final document - even when using the parameter {new:true}

This is the code for the route:

// 3. We check if blockid is in this project
        Block.findById(req.params.blockid)
          .then(block => {
            if (!block) {
              errors.noblock = "Block not found";
              return res.status(404).json(errors);
            }

            // 4. We found the block, so we modify it
            Block.updateOne(
              { _id: req.params.blockid },
              { $set: blockFields },   // data to be updated
              { new: true },           // flag to show the new updated document
              (err, block) => {
                if (err) {
                  errors.noblock = "Block not found";
                  return res.status(404).json(errors);
                }
                console.log(block);
                res.json(block);
              }
            );
          })
          .catch(err => console.error(err));

Instead, this is the output I am getting (Mongoose is on debug mode)

Mongoose output

Any ideas?

Many thanks

Upvotes: 5

Views: 11608

Answers (3)

jmrueda
jmrueda

Reputation: 1428

Thank you @sivasankar for the answer. Here is the updated working version with findOneAndUpdate

mongoose new function findoneandupdate

And here the expected result:

terminal result outputting the document

Upvotes: 1

Muhammad Aadil Banaras
Muhammad Aadil Banaras

Reputation: 1284

you should give second param as object of keys value paris of data, don't pass as $Set : blockfields, just add like below, if it is object containing parameters,

{ $set: blockFields } Because code should be like this

Block.updateOne(
  { _id: req.params.blockid },
  blockFields, // if blockfields is object containing parameters
  { new: true },
  (err, block) => {
    // lines of code
  }
);

For more detail here is link to updateOne function detail updateOne

Upvotes: 0

Şivā SankĂr
Şivā SankĂr

Reputation: 2036

{ new : true } will return the modified document rather than the original. updateOne doesn't have this option. If you need response as updated document use findOneAndUpdate.

Below are the mongoosejs function where you can use { new : true }

  • findByIdAndUpdate()
  • findOneAndUpdate()
  • findOneAndDelete()
  • findOneAndRemove()
  • findOneAndReplace()

Upvotes: 13

Related Questions