Reputation: 11842
I am new in node and mongodb. I am trying to query a different model(Event) from another model(Company).
Basically in Event
model there is a field called company
. I would like to get the company where id is an Event ID.
I have all the event IDs in an array.
let eventIds = [ 5b76a8139dc71a4a12564cd2,
5b9a1685c239342d4635466c,
5b8e753bdbccf803e906aaeb ]
Event Schema --
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}
]
});
In company model --
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);
});
});
I am getting Event.find is not a function
error message. How can I query a different model(event) from another model(company)
Any help is highly appreciated.
Upvotes: 0
Views: 4178
Reputation: 1012
If you're importing your model from an index.js or index.ts file, you had better import the file as:
import YourModel from "./<file>/index"
Upvotes: 0
Reputation: 94
This worked for me:
In my project I pass a Model into some middleware and started seeing this issue so I used mongoose.model('Name of Model')
example: .get(advancedResults(mongoose.model('Store'), 'stores'), getStores)
Upvotes: 0
Reputation: 11842
Not sure why but I had to do this in the following way.
Event.find({ $in: eventIds}, function(err, docs){
To
mongoose.model('Event').find({_id:eventIds}, function(err, docs){
which returned 3 documents which are correct.
Upvotes: 7
Reputation: 59
How are you exporting your EventModel? Assuming you are exporting it like as a module (module.exports = { EventModel }), you want to go "const Event = require('./event.js').EventModel;"
Then simply go with "Event.find(..."
Upvotes: 0
Reputation: 336
Use alias when you require file
EventModel = require('./event.js');
then
EventModel.find({ $in: eventIds}, function(err, docs){
console.log(docs);
});
Upvotes: 1