开发者

Why do I get "cannot call doValidate of undefined" when saving a model using Mongoose.js?

开发者 https://www.devze.com 2023-02-26 05:38 出处:网络
Could someone please help try and explain what I\'m doing wrong using mongoose.js ORM and give me some guidance in how to fix the problem.

Could someone please help try and explain what I'm doing wrong using mongoose.js ORM and give me some guidance in how to fix the problem.

Problem

When trying to save a model using mongoose.js orm I receive an error:

Cannot call method 'doValidate' of undefined

Schema Definition

I'm trying to save the object with this schema:

var myEntity = new Schema({
  objectId            : ObjectId
  ,title             : String
  , decription        : String
  , ownerId           : String
  , start               : {
     something : {
      // ...
     }
   //removed for brevity!
  }
  , end             : {
     something : {
      // ...
     }
   //removed for brevity!
    }
  , useruid           : String
  , _created          : { type : Date, "default": new Date()}
  , _updated          : { type : Date, "default": new Date()}
}
mongoose.model("MyEntity", MyEntity);

Definining the models

I've placed the models in a container so that I can access them by doing:

var xyz = new models['whatever']();

The container object looks like:

var models = {
  MyEntity : mongoose.model("MyEntity"),
};

Creating the model

I create the model, passing in a JSON object with all the right 'mapping' or attributes:

var newEntity = new models.MyEntity(someObj);

Saving the model

Then the code below is ho开发者_如何学Pythonw I save the model:

newEntity.save(function(error) {

                  if (error) {
                    console.log(error);
                  }

                  writePostEntityResponse(newEntity);
                });

I don't see what I'm doing wrong and the error message, although clear, isn't helping me much.


Usually when I get that error it's because I've tried to save a field that doesn't exist, perhaps because I've altered a form or something.

Mongo creates ObjectIds automatically. Have you tried removing that field and seeing what happens?


The order should be important. If you define models before you attach the schema to the models then your dealing with the correct objects.

var schema = new Schema(...);
mongoose.model('ModelName', mySchema)
var models = {
    "foo": mongoose.model('ModelName')
}
var xyz = new models['foo']();
xyz.save();

As to the error message, mongoose has a validation system in build, so whenever you save it, it will validate. By default there are no validation rules so it does nothing. Again it seems like the model object your trying to save is missing something, maybe the schema, maybe the validation code.

0

精彩评论

暂无评论...
验证码 换一张
取 消