Model.find不是猫鼬中的函数

时间:2018-09-24 11:49:08

标签: mongodb mongoose collections

我是node和mongodb的新手。我正在尝试从另一个模型(公司)查询另一个模型(事件)。

基本上在Event模型中,有一个名为company的字段。我想获得ID为事件ID的公司。

我将所有事件ID放在一个数组中。

 let eventIds = [ 5b76a8139dc71a4a12564cd2,
  5b9a1685c239342d4635466c,
  5b8e753bdbccf803e906aaeb ]

事件架构-

var EventSchema = new Schema({
        title:{type:String,require:true,index:true},
        description:{type:String,require:false},
        companies:[
            {type:Schema.Types.ObjectId,ref:"Company",require:true,index:true}
        ]
});

在公司模式下-

var mongoose = require('mongoose'),
    Schema = mongoose.Schema,
    Event = require('./event.js');

var CompanySchema = new Schema({
        name:{type:String,require:true,index:true},
        description:{type:String,require:false}},{
        //no auto indexing at the beginning
        autoIndex:true,

        //no strict to save changes in the valuesBeforeChange field.
        strict:false}
);

CompanySchema.static("searchCompanies",function(callback,criteria){

    "use strict";
    var That = this;
    var query = That.find();

    async.waterfall([

         function(callback){
             let eventIds =  [5b76a8139dc71a4a12564cd2,5b9a1685c239342d4635466c,5b8e753bdbccf803e906aaeb ];
             Event.find({ $in: eventIds}, function(err, docs){
                   console.log(docs);
             });
     }

],function(err,companyResultObj){
         callback(err,companyResultObj);
    });
});

我收到Event.find is not a function错误消息。如何从另一个模型(公司)查询另一个模型(事件)

我们非常感谢您的帮助。

4 个答案:

答案 0 :(得分:1)

在需要文件时使用别名

EventModel = require('./event.js');
then 
EventModel.find({ $in: eventIds}, function(err, docs){
   console.log(docs);
});

答案 1 :(得分:0)

您如何导出EventModel? 假设您像模块一样将其导出(module.exports = {EventModel}), 你想去“ const Event = require('./ event.js')。EventModel;”

然后只需使用“ Event.find(...”

答案 2 :(得分:0)

不确定为什么,但是我必须按照以下方式进行操作。

Event.find({ $in: eventIds}, function(err, docs){

收件人

mongoose.model('Event').find({_id:eventIds}, function(err, docs){

返回了3个正确的文档。

答案 3 :(得分:0)

这对我有用:

在我的项目中,我将一个模型传递给一些中间件并开始看到这个问题,所以我使用了 mongoose.model('Name of Model')

示例:.get(advancedResults(mongoose.model('Store'), 'stores'), getStores)

相关问题