1

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

Zac Feng
  • 37
  • 6

2 Answers2

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

robertklep
  • 198,204
  • 35
  • 394
  • 381
0

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.

abrahamebij
  • 143
  • 1
  • 8
  • I keep getting the same error, `TypeError: Cannot read properties of undefined (reading 'findOne')` – Zac Feng Jun 20 '22 at 07:35
  • Then there's probably an error with your database. Try checking viewing the data using the `mongo` command or [Download Studio3t](https://studio3t.com/download/) for a better view. – abrahamebij Jun 20 '22 at 07:48