How to exports many mongoose models modules in node.js

Tags: , , , ,

I have 2 models like this

const Db = mongoose.model('db', dbSchema); 
const Beacon = mongoose.model('beacon', dbSchema2);

Now I want to export them. First I export Db and everything is fine. I can do an HTTP request with it.

module.exports = Db;

However, when I try to export ´the 2nd one outside, it stops functioning. The functions below will return a blank JSON file as a response.

module.exports = Db;
module.exports = Beacon;

This won’t work either. It returns an error handler saying all my functions in the handler is not function.

module.exports = {
Db, Beacon

This is the function on the file I import the models.

router.get('/data/:id', function(req, res, next) {
    Db.findOne({ _id: }).then(function(db) { 

The return from the handler is Db.findOne is not a function.

Is there any way to export them both? Thank you. Here is the importing on another file

const Db = require('./db.js');
const Beacon = require('.db.js');


This should work:

Exporting in one file

module.exports = { Db, Beacon };

Then, importing in another file

const { Db, Beacon } = require('path-to-db.js');

// use them

Notice that this uses the ECMAS 6 Destructuring Assignment (additional info on MDN)

Source: stackoverflow