0

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).

stackers
  • 2,701
  • 4
  • 34
  • 66
  • It's possible that you have a circular dependency which causes the first pass through trying to load it to get an empty object. Try a very simple file that does `console.log(require('articles.js'))` and nothing else. – jfriend00 Aug 11 '19 at 21:01
  • Okay you were right, I found where there's a circular dependency. In single.js I require another model file which requires another query, which requires the file I have above that's outputting the errors. Is there a standard way of avoiding this, when both files need to be able to access each other? – stackers Aug 11 '19 at 21:13

0 Answers0