I have a schema and specify login is unique is true. When I use findByIdAndUpdate and pass query $set to update an user object, it did not throw back error when login is dup. Does anyone know why and how I should update an object and force schema validation?
Thanks!
// UserSchema.js
var schema = new Schema({
login: {
required: true,
unique: true
},
password: {
index: true,
type: String
}
});
// Update
UserSchema.findByIdAndUpdate('someID', { '$set': { login: 'abc' } }, function (error, user) {
callback(error, user);
});
I have a schema and specify login is unique is true. When I use findByIdAndUpdate and pass query $set to update an user object, it did not throw back error when login is dup. Does anyone know why and how I should update an object and force schema validation?
Thanks!
// UserSchema.js
var schema = new Schema({
login: {
required: true,
unique: true
},
password: {
index: true,
type: String
}
});
// Update
UserSchema.findByIdAndUpdate('someID', { '$set': { login: 'abc' } }, function (error, user) {
callback(error, user);
});
Share
edited Sep 19, 2013 at 3:28
Nam Nguyen
asked Sep 18, 2013 at 17:00
Nam NguyenNam Nguyen
5,77014 gold badges59 silver badges73 bronze badges
6
- Nam, Are u using client side validation through JavaScript to check for duplicate login attempt? This requires interaction with the server. Isn't it? Moreover your question needs an edit for others to understand it clearly. – Rajesh Paul Commented Sep 19, 2013 at 3:38
- @Rajesh Paul, my question is related to Node.js and Mongoose.js, it is not about client side though. – Nam Nguyen Commented Sep 19, 2013 at 3:43
- Ok, then its not my area. – Rajesh Paul Commented Sep 19, 2013 at 3:57
- no problem @ Rajesh Paul, thanks! – Nam Nguyen Commented Sep 19, 2013 at 4:19
-
You need to give
login
atype
value in your schema. Maybe that's just a typo as Mongoose should be throwing an exception if you leave it out. – JohnnyHK Commented Sep 20, 2013 at 13:16
2 Answers
Reset to default 5You simply need to set runValidators to true:
findByIdAndUpdate(req.params.id, {$set: data}, {runValidators: true}, function (err, doc) {
if (err) {
// Handle validation errors
}
})
More here: http://mongoosejs./docs/api.html#findOneAndUpdate
Using the shorthand helper methods in Mongoose bypasses validation, so you need to use a 3 step approach:
- Find
- Edit
- Save
For example:
// 1: Find
UserSchema.findById( 'someID',
function (err, user) {
if(!err){
// 2: Edit
user.login = 'abc';
// 3: Save
user.save(function (err, user) {
if (err) {
console.log(err);
return;
}
console.log('User saved: ' + user);
});
}
}
);
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742403664a4437408.html
评论列表(0条)