模型的findOne方法上的Mongoose TypeError [英] Mongoose TypeError on a model's findOne method
问题描述
在一些旧代码中出现以下TypeError。
The following TypeError cropped up in some old code.
TypeError: Object #<Object> has no method 'findOne'
最近受影响的模型定义了两个新的静态方法和那些方法参考外部模型。在退出新的静态方法之后,我能够确定外部模型的require语句的根本原因。该模式如下所示:
The Model that was affected recently had two new static methods defined and those methods referenced external models. After backing out the new static methods, I was able to determine the root cause to be the require statements of the external models. The pattern looks like the following:
var UserModel = require('./user');
var GroupSchema = new Schema({
name: String,
users: [{ type : Schema.ObjectId, ref: 'UserModel'}],
});
GroupSchema.statics.findSomeUsers = function(group, callback) {
this.find({name : session_user._id}, function(err, groups) {
UserModel.find({_id : {$in : group.users}}, function(err,patients) {
// do magic
});
});
};
module.exports = mongoose.model('GroupModel', GroupSchema);
应用程序中有一个代码片段调用GroupModel.findOne({name:'gogo'} )导致TypeError。当我在GroupSchema中删除UserModel的require语句时,应用程序代码再次起作用。
There is a code fragment in the application that calls GroupModel.findOne({name:'gogo'}) that leads to the TypeError. when I remove the require statement for the UserModel in the GroupSchema, app code works again.
为什么Javascript开始认为findOne()是一个添加了require语句的实例方法?
Why does Javascript start to think findOne() is an instance method with the addition of the require statement?
推荐答案
已知node.js问题。这意味着你需要在代码中的某个地方进行循环,而node.js禁止它。
It's known node.js issue. It means that you have looping require somewhere in your code and node.js forbids it.
正确的方法是使用 mongoose。 model
方法。因此,您应使用 mongoose.model('UserModel')
而不是 UserModel
变量。因此,当 findSomeUsers
将被调用时,mondoose将获取 UserModel
并调用其 find
方法。
The right way to do it is by using mongoose.model
method. So, instead of UserModel
variable you shall use mongoose.model('UserModel')
. So, when findSomeUsers
will be called mondoose will fetch UserModel
and invoke its find
method.
GroupSchema.statics.findSomeUsers = function(group, callback) {
this.find({name : session_user._id}, function(err, groups) {
mongoose.model('UserModel').find({_id : {$in : group.users}}, function(err,patients) {
// do magic
});
});
};
这篇关于模型的findOne方法上的Mongoose TypeError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!