I know it is an old question and I am aware of the usage that I'm not suppose to call findOne function on instance of model, instead on the model itself.
Here is my corporation.model.js:
const mongoose = require('mongoose');
const corporationSchema = new mongoose.Schema(
{
name: {
type: String,
required: true,
trim: true,
},
logo: {
type: String,
required: true,
},
description: {
type: String,
required: false,
trim: true,
},
companyType: {
type: String,
required: true,
},
code: {
type: String,
required: true,
immutable: true,
unique: true,
},
},
{ timestamps: true }
);
corporationSchema.statics.fetchOneWithAssociations = async function fetchOneWithAssociations(
id
) {
// func definition
};
corporationSchema.statics.findByName = async function findByName(text) {
// func definition
};
module.exports = mongoose.model('Corporation', corporationSchema);
and my event.model.js:
const mongoose = require('mongoose');
const { of } = require('await-of');
const Corporation = require('./corporation.model');
const EventSchema = new mongoose.Schema(
{
title: { type: String, required: true },
subtitle: { type: String },
corporationId: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Corporation',
required: true,
},
},
{ timestamps: true }
);
EventSchema.statics.findByCorporationId = async function findByCorporationId(
corporationId,
filterQuery,
limit,
offset,
sort
) {
try {
let corporation = {};
let logoErr = {};
let totalEvents = 0;
let events = [];
if (corporationId) {
[totalEvents, errCount] = await of(
this.count({ corporationId, ...filterQuery })
);
[events, err] = await of(
this.find({ corporationId, ...filterQuery })
.sort(sort)
.limit(limit)
.skip(offset)
);
console.log('Corporation', Corporation);
[corporation, logoErr] = await of(
Corporation.findOne({ _id: corporationId }, 'logo')
);
if (err || errCount) {
throw err;
}
}
return {
events,
count: totalEvents,
logo: corporation.logo,
};
} catch (e) {
throw e;
}
};
EventSchema.statics.exceptByCorporationId = async function exceptByCorporationId(
corporationId,
filterQuery,
limit,
offset,
sort
) {
// func definition
};
module.exports = mongoose.model('Event', EventSchema);
line console.log('Corporation', Corporation); prints an object i.e. {}. Ok I understand, it is a problem but here is my question. why? I mean it seems like I have created my model correctly. Didn't I. Why I'm getting my model as instance instead of my model class itself.