简体   繁体   中英

Mongoose Models: Cannot read properties of undefined (reading 'findOne')

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM