导出异步回调中可用的Mongoose连接?

时间:2017-08-14 01:14:59

标签: node.js mongodb mongoose

我在Node.js中编码很新,我通过mongoose创建了一个数据库连接,然后将数据库对象导出到我的主app.js文件中:

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

exports.db = db;

这里我试图使用该数据库连接来执行CRUD操作:

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

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

错误是:

  

TypeError:db.collection不是函数

我认为这是因为connectdb.js的调用是异步的,而require中的app.js是同步的 - 所以它是未定义的当我执行db.collection ??如何使用Mongoose来避免这个错误?

目标:我希望能够在db.collection.insertOne()

中致电app.js

我发现了一个有点相关的话题,但它并没有使用Mongoose,所以我对如何解决这个问题感到困惑:How to export an object that only becomes available in an async callback?

1 个答案:

答案 0 :(得分:0)

回答我自己的问题:

app.js需要一个猫鼬模型。因此,我没有在主db.collection中执行app.js,而是将CRUD操作路由到控制器文件中定义的函数。

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

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

以下是路线:

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

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

这是实际功能:

//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
    }
  });
};