I am able to create documents with the help of Mongoose in Node.js, but not able to update or delete them.
I tried doing it on the terminal with the following command:
db.news.updateOne({name: 'Mishra'}, {$set :{name:'mishra'}})
Here's the code I have tried, but it doesn't work:
const mongoose = require('mongoose');
mongoose.connect('mongodb://127.0.0.1:27017/newDB');
const newSchema = mongoose.Schema({
name: String,
age: Number
});
const user = mongoose.model('new', newSchema);
const newUser = new user({
name: 'Sharabh',
age: 22
});
// Uncomment to check if user exists
// console.log(Boolean(user.find({name: 'Mishra'})))
user.updateOne({name: 'Mishra'}, {$set: {name: 'mishra'}});
// Uncomment to save
// user.save();
// newUser.save();
Your user.updateOne()
method is an asynchronous task. You need to wait for the task to complete.
If you are using Modules (i.e import
statements) then you can do a top level await
:
const result = await user.updateOne({name: 'Mishra'},{$set: {name: 'mishra'}});
Or if you are using CommonJS (i.e require
statements) then you can do:
user.updateOne({name: 'Mishra'},{$set: {name: 'mishra'}})
.then((result) => {
console.log(result);
})
.catch((err) => {
console.log(err);
});
If this is going to be in a post request from a form you submit then you can mark the callback function as async
then use await
in the update like so:
const user = mongoose.model('new', newSchema)
app.post('/', async (req, res, next) => { // < Note the use of async
try {
const updated = { // < Get the data from your form post
name: req.body.name,
age: req.body.age
}
const result = await user.updateOne({name: 'Mishra'},{$set: updated});
console.log(result);
res.status(201).json({
updatedUser : result
});
} catch(err) {
next(err);
}
});