[英]Why do I get “cannot call doValidate of undefined” when saving a model using Mongoose.js?
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. 有人可以帮忙尝试使用mongoose.js ORM解释我做错了什么,并为我提供一些解决问题的指导。
When trying to save a model using mongoose.js orm I receive an error: 尝试使用mongoose.js orm保存模型时,出现错误:
Cannot call method 'doValidate' of undefined 无法调用未定义的方法“ doValidate”
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);
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"),
};
I create the model, passing in a JSON object with all the right 'mapping' or attributes: 我创建模型,并传入具有所有正确“映射”或属性的JSON对象:
var newEntity = new models.MyEntity(someObj);
Then the code below is how 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. 我看不到我在做什么错,错误消息虽然很清楚,但对我没有太大帮助。
The order should be important. 顺序应该很重要。 If you define
models
before you attach the schema to the models then your dealing with the correct objects. 如果在将架构附加到
models
之前定义models
,那么您将处理正确的对象。
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.
同样,您尝试保存的模型对象似乎丢失了某些内容,可能是架构,可能是验证代码。
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. Mongo自动创建ObjectId。 Have you tried removing that field and seeing what happens?
您是否尝试过删除该字段并查看会发生什么?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.