I\'m trying to update an instantiated model (\'Place\' - I know it works from other routes) in a MongoDB and have spent a while trying to properly do so. I\'m also trying t
You have to find the document before updating anything:
Place.findById(req.params.id, function(err, p) {
if (!p)
return next(new Error('Could not load Document'));
else {
// do your updates here
p.modified = new Date();
p.save(function(err) {
if (err)
console.log('error')
else
console.log('success')
});
}
});
works for me in production code using the same setup you have. Instead of findById you can use any other find method provided by mongoose. Just make sure you fetch the document before updating it.
you could do something similar based on the illustration below
Updated:
In My solution: I have created a model, controller and route to depict the similar scenario (interacting with MongoDB method like updating/creating data to the database)
in Nodejs MVC framework with MongoDB as the database
// user.js - this is the user model
const mongoose = require('mongoose')
const validator = require('validator')
const User = mongoose.model('User', {
name: {
type: String,
required: true,
trim: true
},
email: {
type: String,
required: true,
trim: true,
lowercase: true,
validate(value) {
if (!validator.isEmail(value)) {
throw new Error('Email is invalid')
}
}
},
password: {
type: String,
required: true,
minlength: 7,
trim: true,
validate(value) {
if (value.toLowerCase().includes('password')) {
throw new Error('Password cannot contain "password"')
}
}
},
age: {
type: Number,
default: 0,
validate(value) {
if (value < 0) {
throw new Error('Age must be a positive number')
}
}
}
});
module.exports = User
// userController.js**
exports.updateUser = async(req, res) => {
const updates = Object.keys(req.body)
const allowedUpdates = ['name', 'email', 'password', 'age']
const isValidOperation = updates.every((update) => {
allowedUpdates.includes(update))
if (!isValidOperation) {
return res.status(400).send('Invalid updates!')
}
try {
const user = await UserModel.findByIdAndUpdate(req.params.id,
req.body, { new: true, runValidators: true })
if (!user) {
return res.status(404).send({ message: 'You do not seem to be registered' })
}
res.status(201).send(user)
} catch (error) {
res.status(400).send(error)
}
}
// **router.js**
router.patch('/user/:id', userController.updateUser)
I hope this would help anyone, you can also Read more.
I think your problem is that you are using node 0.4.0 - try moving to 0.2.6 with an it should work. There is an issue logged on github with the bodyDecoder not populating the req.body.variable field in node >= 0.3.0.
So now you can find and update directly by id, this is for Mongoose v4
Place.findByIdAndUpdate(req.params.id, req.body, function (err, place) {
res.send(place);
});
Just to mention, if you needs updated object then you need to pass {new: true}
like
Place.findByIdAndUpdate(req.params.id, req.body, {new: true}, function (err, place) {
res.send(place);
});
Now, i think you can do this :
Place.findOneAndUpdate({name:req.params.name}, req.body, function (err, place) {
res.send(place);
});
You can find by id too :
Place.findOneAndUpdate({_id:req.params.id}, req.body, function (err, place) {
res.send(place);
});