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
You can simply use callbacks
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 isrequire()
‘d.It’s perfectly okay with Mongoose to create models without a connection being present.
Something like this:
If you need access to the connection from other parts of your app, you can use
mongoose.connection