admin管理员组文章数量:1336415
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);
});
}
}
);
本文标签: javascriptfindByIdAndUpdate set does not check for uniqueStack Overflow
版权声明:本文标题:javascript - findByIdAndUpdate $set does not check for unique? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742403664a2468381.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论