With Mongoose, how to separate the model functions in multiple files

Viewed 24

I have a unique file that contains all the functions I apply to my mongoose model.

But as I plan to have a lot of functions I would like to have several sub-files that contain these functions.

For example I would like to have a "user functions" sub-file and a "product functions" sub-file. I can't manage to do the import/export to get this result.

For now I have this file of functions:

const Schemas = require('./Schemas');

mongoose.connect('mongodb://localhost/test', () => {
    console.log('Connected to MongoDB');
}, (err) => {
    console.log(err);
});

async function createUser(name, email) {
    try {
        const user = new Schemas({
            name,
            email
        });
        await user.save();
        console.log('User created');
    } catch (e) {
        console.log("### ERROR: ",e.message);
    }
}

async function createProduct(name, price, userName) {
    try {
        const product = new Schemas({
            name,
            price
        });
        await product.save();
        const user = await Schemas.findOne({name: userName});
        user.products.push(product);
        await user.save();
        console.log('Product created');
    } catch (e) {
        console.log("### ERROR: ",e.message);
    }
}

createUser('John', 'john@doe.com');
createProduct('Product_name', 100, 'John');

I would like the createProduct function to be in another file!

I don't know if it is important. This is my Schemas.js file:

const { Schema } = mongoose;

const productSchema = new Schema({
      name: String,
      price: Number
});

const userSchema = new Schema({
      name: String,
      email: String,
      products: [productSchema]
});

module.exports = mongoose.model('Schemas', userSchema);
0 Answers
Related