0

I'm new to coding in Node.js and I've created a DB connection through mongoose, then exporting the database object into my main app.js file:

// db.js
var mongoose = require("mongoose");
var uri = /*The URL*/;
var db = mongoose.connect(uri, {
    useMongoClient: true
});

exports.db = db;

Here I'm trying to use that DB connection to perform CRUD operations:

// app.js
var db = require('./db');

app.post('/', function (req, res) {
    db.collection(/* … */); // throws error
});

The error is:

TypeError: db.collection is not a function

I think this is because that the call of connect in the db.js is asynchronous and the require in app.js is synchronous - so it'll be undefined when I execute db.collection?? How can Mongoose be used to avoid this error?

Goal: I want to be able to call db.collection.insertOne() within my app.js

I found a somewhat related topic but it doesn't use Mongoose, so I'm confused as to how to resolve this issue: How to export an object that only becomes available in an async callback?

James Li
  • 133
  • 10
  • Have a look at the mongoose docs. mongoose.connect doesn't return an object with a collection function on it at all. Plus, this isn't how you typically insert things when using Mongoose. – Paul Aug 14 '17 at 01:50
  • @Paul I'm looking at creating methods under the Schemas, and then calling `var XXX = mongoose.model('XXX', xxxSchema)` in `app.js` then using the methods under newly-created objects. Is this the right direction? – James Li Aug 14 '17 at 03:31
  • You need to create mongoose models to query that document and export those models rather than exporting db object. – Shubham Jain Aug 14 '17 at 03:32
  • Figured this out, thanks Paul and Shubham, I had the model and all the methods created earlier but never went around to understand how to use it. Thanks again for the tips! – James Li Aug 14 '17 at 04:41

1 Answers1

0

Answering my own question:

It'll need a mongoose model in the app.js. So instead of doing db.collection in the main app.js, I ended up routing the CRUD operations to functions defined in the controller file.

//app.js
var app = express();
var router = express.Router();
app.use(router);
require("./Routes")(router);

router.get("/xxx", xxx.get);

Here are the routes:

//routes.js - takes care of routing URLs to the functions
var XXX = require('../xxx');

module.exports = function(router){
 router.get('/XXX', XXX.get)
};

Here is the actual function:

//xxx.js - functions defined here
exports.get = function (req, res) {
  XXX.getAll(req.body, function(err, result){
    if (!err) {
        return res.send(result); // Posting all the XXX
    } else {
        return res.send(err); // 500 error
    }
  });
};
James Li
  • 133
  • 10