-1

I am trying to make a database file that delivers connection, model etc for mongoose (MongoDb).

So when I return the Mongoose Model, the create method becomes "undefined".

database.js

//model connection 
exports.MongoModel = async function ({connectionName, collection, schema}){
    //get connection data 
    const databaseData = connectionsArray[connectionName];

    //create url 
    const mongoUrl = `${dbUrl}${databaseData.databaseName}`;

    //connection 
    const connection = Mongoose.createConnection(mongoUrl, databaseData.options);

    //model with schema
    const Model = connection.model('files',schema);

    console.log(Model.create);// displays [Function: create] in console

    //return model
    return Model
}//MongoModel ends 

When imported to the other file

FileUploads.js

const { MongoModel } = require('@src/config/database');


const FilesModel = MongoModel({connectionName:'files', collection: 'files', schema: FilesSchema});

console.log(FilesModel); // Displays Promise { Model { files } }
console.log(FilesModel.create); // Displays undefined

Note: I am very new to this platform so please pardon me typo's.

Mehadi Hassan
  • 1,160
  • 1
  • 13
  • 33

2 Answers2

0

Well try it like this:

//model connection 
function MongoModel({connectionName, collection, schema}){
    //get connection data 
    const databaseData = connectionsArray[connectionName];

    //create url 
    const mongoUrl = `${dbUrl}${databaseData.databaseName}`;

    //connection 
    const connection = Mongoose.createConnection(mongoUrl, databaseData.options);

    //model with schema
    const Model = connection.model('files',schema);

    console.log(Model.create);// displays [Function: create] in console

    //return model
    return Model
}//MongoModel ends 

module.exports = { MongoModel }

You need to export an Object with your MongoModel in it. Now you should be able to destructure it at the import statement.

And i dont see a reason to use async here

bill.gates
  • 14,145
  • 3
  • 19
  • 47
0

In your code 'MongoModel' references an async function which always returns a Promise. That is why you see Promise { Model { files } } when you log the object to your console. Two things you can do are:

Option 1: Remove the 'async' key word from your function declaration. This way your function returns your model object instead of a promise. Option 2: Add a callback to get the data returned by the promise as shown below:

MongoModel({connectionName:'files', collection: 'files', schema: FilesSchema})
    .then((FileModel) => {
         console.log(FileModel.create); // should display [Function: create]
});
Iyanu Adelekan
  • 396
  • 2
  • 7