I am trying to figure out why my module isn't loading properly. It's a mongoose model, but even having it just return a string sometimes returns the empty object, so it seems like it's something to do with node.
articles/models/articles.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var articleSchema = new Schema({
title: String,
slug: String,
author: { type: mongoose.Schema.ObjectId, required: true},
likes: {type: Number, default: 0},
comments: {type: Number, default: 0},
outro: String,
metadescription: String,
metaimage: String,
},{timestamps: true});
//queries
articleSchema.statics.new = require('../queries/new.js');
articleSchema.statics.get = require('../queries/get.js');
articleSchema.statics.single = require('../queries/single.js');
articleSchema.statics.update = require('../queries/update.js');
articleSchema.statics.delete = require('../queries/delete.js');
//articleSchema.statics.updateCommentCount = require('../queries/updateCommentCount.js');
var model = mongoose.model('articles', articleSchema);
//save to exports
module.exports = 'hi';
And here I try to call it:
var Articles = require('../../articles/models/articles.js');
console.log('a',require('../../articles/models/articles.js'));
console.log('b',Articles);
setTimeout(()=>{
console.log('c',require('../../articles/models/articles.js'));
console.log('d',Articles);
},1000);
But this is what it outputs:
a: {}
b: {}
c: hi
d: {}
Why is this happening? Where is the empty object coming from? It's clearly finding the correct file because there's no errors.
If I move module.exports = 'hi' to the top of articles.js though, then I get the proper "hi" for a, b, c, and d. But I'm trying to make it return the model object created in that document.
I can't figure out where the problem is occurring.
Edit: this seems to be a circular dependency issue. The Articles and Comments models both have functions that reference each other, because they both need to. I don't understand why they can't, or how to avoid with (with still keeping my code clean).