Twinsen
Twinsen

Reputation: 893

Check the data before updating in MongoDb

I use findAndModify, and it's works.

This is my Schema

var userSchema = new mongoose.Schema({
    _id               : ObjectId,
    username          : String,
}, {
    safe              : true
});

If I insert username : 100, my username in Schema change in Double.

Can i check the elements before update, and update only if username is String?

Upvotes: 1

Views: 1595

Answers (1)

mnemosyn
mnemosyn

Reputation: 46291

Don't be fooled by Mongoose, which is merely a 'helper' (though my feeling is it mostly adds confusion).

It's important to understand MongoDB by itself. MongoDB has no schema. You don't even need to declare a collection before using it, e.g. on a newly started mongodb, first command ever: db.bla.insert({"Name":"john"}); just works. Then, do db.bla.insert({"xf":1456}); also works, even though it is completely different from the first document.

Hence, MongoDB can't validate your object according to some kind of schema, and it doesn't have to. The question is whether your code can cope with that, or not. In most cases, it makes sense to have a strict schema. Enforcing the schema must be done by your application code, though I believe Mongoose offers a helper, doc.validate() for this.

Upvotes: 3

Related Questions