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 a type 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
 |  Show 1 more ment

2 Answers 2

Reset to default 5

You 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:

  1. Find
  2. Edit
  3. 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