skip to Main Content

I try to import a model from the file where I create it (the same file where I connect the database) and when I try to work with it, it is "undefined".

const { model } = require("../database");

model.findOne(. . .).then(. . .

This is the file I connect/create with

mongoose.connect(mongoUri, {
    dbName: "x"
}).then(async () => {

    const db = mongoose.connection;

    db.on('error', err => console.error);

    const schema = new mongoose.Schema({
        . . .
    });

    const model = mongoose.model('userprofiles', schema );

    module.exports = {
        mongoose,
        db,
        model
    };
});

I went through many posts on GitHub Issues and here on StackOverflow and none have given me a concise, working answer

I tried with "autoCreate" that I saw in an Issue on Github, but it didn’t work, the same thing happened

mongoose.connect(mongoUri, {
    dbName: "x",
    autoCreate: true
}).then(async () => {

    . . .
    
    const model = mongoose.model('userprofiles', schema );
    await model.init();

    module.exports = {
        mongoose,
        db,
        model
    };
});

I should clarify that if I work directly on the model file it works perfectly well

2

Answers


  1. You can simply use callbacks

    const { model } = require("../database");
    
    model.findOne({_id : 12489e}, function (err, data) {
      if (err) {
        console.log(err)
      } else {
        console.log(data);
      }
    });
    

    Note: The _id depends on whatever you are querying for.
    Could be name or whatever.

    Also make sure that you’re running the mongod command in your terminal.

    Login or Signup to reply.
  2. You need to separate your exports from creating a database connection. Modules are loaded synchronously, so if you declare module.exports inside an (asynchronous) callback, it won’t be declared at the time the file is require()‘d.

    It’s perfectly okay with Mongoose to create models without a connection being present.

    Something like this:

    mongoose.connect(mongoUri, {
        dbName: "x"
    }).then(() => {
        const db = mongoose.connection;
        db.on('error', err => console.error);
    });
    
    const schema = new mongoose.Schema({
        . . .
    });
    
    const model = mongoose.model('userprofiles', schema );
    
    module.exports = { mongoose, model };
    

    If you need access to the connection from other parts of your app, you can use mongoose.connection

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search