Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
453 views
in Technique[技术] by (71.8m points)

javascript - How to get updated document back from the findOneAndUpdate method?

I am using MongoDB with node js , i used npm install mongodb

I want to update an existing document and return the updated document , the document is updated correctly . but it returns the old document means the original document before update . i have used the returnNewDocument:true parameter but no use .

            var filter = {
                '_id': object_id
            },
            update = {
                $set: { "status" : data["status"] },
                $push: {
                    "statusHistory": {
                        $each: [{ status:data["status"],statusChangedTime:data["statusChangedTime"],comment:data["comment"]}],
                        $position:0,
                    }
                },
            }
            ,options = {
                //upsert: false,
                //multi: false,
                returnNewDocument: true
            };

            col.findOneAndUpdate(filter, update, options,function(err, res) {
                if (err) {

                    console.log(err);
                }else {

                    console.log(res);
                }
            });

the response is

{ lastErrorObject: { updatedExisting: true, n: 1 },
  value: 
   { 
//original document
   },     
  ok: 1 }

when i directly go to mongoDB through terminal and try

db.MyCollection.find().pretty();

the document is updated correctly, it just returns the original instead of updated one.

Stuck here for 2 hours, any help is appreciated

in package.json

"mongodb": "^2.1.4",
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The Node.js driver documentation doesn't mention a returnNewDocument option for findOneAndUpdate() (which is an option for the MongoDB shell command with the same name).

Instead, it mentions an option called returnOriginal, which defaults to true. Try using that option, setting it to false to return the updated document instead of the original.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...