Let's say I have the following schema
var userSchema = new Schema({
name : String
});
var User = mongoose.model('User',userSchema);
EDIT: If an user trying to update field, that does not exists, I need throw exception. My question is how can I check that an updating field does not exists in the updating document. Here is a little example what I need:
app.post('/user/update/:id', function (req, res) {
var field = req.param('field'),
value = req.param('value'),
id = req.param('id');
User.findOne({_id: id},function(err, user){
if(err) throw err;
if (user) {
user[field] = value; // Here is I need to check that field is exists
// in user schema. If does't I have to throw
// an execption.
user.save(function (err){
return res.send(200);
});
}
})
});
Try adding $exists
to the query parameter of update(). This will allow you to only update documents if a certain field exists (or not).
http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24exists
From the Mongoose v3.1.2 guide:
The strict option, (enabled by default), ensures that values added to our model instance that were not specified in our schema do not get saved to the db. NOTE: do not set to false unless you have good reason.
The strict option may also be set to "throw" which will cause errors to be produced instead of ignoring the bad data.
var CollectionSchema = new Schema({name: 'string'}, {strict: 'throw'});
Collection.findById(id)
.exec(function (err, doc) {
if (err) {// handle error};
// Try to update not existing field
doc['im not exists'] = 'some';
doc.save(function (err) {
if (err) {
// There is no an errors
}
return res.json(200, 'OK');
});
});
In the expample above I don't get an error when I do update a not existing field.
You can check if the field
exists in the schema
by using .schema.path()
. In your specific use case you can do the following:
app.post('/user/update/:id', function (req, res) {
var field = req.param('field'),
value = req.param('value'),
id = req.param('id');
User.findOne({_id: id},function(err, user){
if(err) throw err;
if (user) {
if(User.schema.path(field)) {
user[field] = value;
} else {
throw new Error('Field [' + field + '] does not exists.');
}
user.save(function (err){
return res.send(200);
});
}
});
});