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
532 views
in Technique[技术] by (71.8m points)

javascript - .updateOne on MongoDB not working in Node.js

I have the following code:

connection((db) => {
            db.collection('orders')
                .updateOne(
                    { "_id": req.body._id}, // Filter
                    {"name": req.body.name} // Update
                )
                .then((obj) => {
                    console.log('Updated - ' + obj);
                    res.redirect('orders')
                })
                .catch((err) => {
                    console.log('Error: ' + err);
                })
        })

I want to change the name in the order but it doesn't update it. The result in the console is

Updated - {"n":0,"nModified":0,"ok":1}

I tried to read the documentation but it's horrific

EDIT: {$set: {"name": req.body.name}}, didn't work as well

EDIT 2: The passed ID matches the _id in the database. Could it be a problem that I'm querying for plain text ID while in the database it is referred to as "ObjectId('5a42ja...')"

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

Maybe you should use "$set" in your update query like this :

{$set: {"name": req.body.name}}, // Update

More information in documentation

EDIT

If it doesn't work, this is probably because there is no match with your filter.

Maybe you should try to match with an ObjectId like this :

var ObjectID = require('mongodb').ObjectID;

// In your request
{ "_id": ObjectID(req.body._id)}, // Filter

Hope it helps.


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

...