Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
461 views
in Technique[技术] by (71.8m points)

Why Mongoose doesn't validate on update?

I have this code

var ClientSchema = new Schema({
  name: {type: String, required: true, trim: true}
});

var Client = mongoose.model('Client', ClientSchema);

Using express, I create a new client with this code

var client = new Client(req.body);
client.save(function(err, data) {
  ....
});

If I leave the name field empty on the form, mongoose doesn't allow to create the client because I set it as required on the schema. Also, if I leave spaces before and after the name, mongoose delete that spaces before save.

Now, I try to update a client with this code

var id = req.params.id;
var client = req.body;
Client.update({_id: id}, client, function(err) {
  ....
});

It let me to change the name, but if I leave it empty on the form, mongoose doesn't validate and save an empty name. If I add empty spaces before and after the name, it save the name with spaces.

Why mongoose validate on save but not on update? I'm doing it in the wrong way?

mongodb: 2.4.0 mongoose: 3.6.0 express: 3.1.0 node: 0.10.1

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As of Mongoose 4.0 you can run validators on update() and findOneAndUpdate() using the new flag runValidators: true.

Mongoose 4.0 introduces an option to run validators on update() and findOneAndUpdate() calls. Turning this option on will run validators for all fields that your update() call tries to $set or $unset.

For example, given OP's Schema:

const ClientSchema = new Schema({
  name: {type: String, required: true, trim: true}
});

const Client = mongoose.model('Client', ClientSchema);

Passing the flag on each update

You can use the new flag like this:

const id = req.params.id;
const client = req.body;
Client.update({_id: id}, client, { runValidators: true }, function(err) {
  ....
});

Using the flag on a pre hook

If you don't want to set the flag every time you update something, you can set a pre hook for findOneAndUpdate():

// Pre hook for `findOneAndUpdate`
ClientSchema.pre('findOneAndUpdate', function(next) {
  this.options.runValidators = true;
  next();
});

Then you can update() using the validators without passing the runValidators flag every time.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...