gridfs-stream和mongoose> = 4.11.0连接设置

时间:2017-09-11 17:22:16

标签: node.js mongodb mongoose

我一直在使用带有以下设置的旧版本(< 4.11.0)mongoose的gridfs-stream:

    var grid = require("gridfs-stream");
    var mongoose = require("mongoose");
    mongoose.connect(connectionString);
    grid.mongo = mongoose.mongo;
    var gfs = grid(mongoose.connection.db);

这些设置都可以正常使用。更新为mongoose 4.11.11后,mongoose连接设置应更改为(第3行):

    mongoose.connect(connectionString, {useMongoClient: true});

但是,现在不再定义mongoose.connection.db了。如何更改上述代码以使其再次工作?非常感谢。

1 个答案:

答案 0 :(得分:1)

我找到了一个解决方案,它使用deasync并对我现有的所有代码进行最小的更改。然而,它看起来并不理想,所以任何建议将不胜感激:

    var grid = require("gridfs-stream");
    var mongoose = require("mongoose");
    var deasync = require("deasync");

    //Connect to mongodb
    mongoose.Promise = global.Promise;
    mongoose.connect(connectionString, {useMongoClient: true});

    //Get the connection setting
    var getConnDb = function () {
        var connDb;
        mongoose.connection.then(function (conn) {
            connDb = conn.db;
        });
        while (connDb === undefined) {
            deasync.runLoopOnce();
        }
        return connDb;
    };

    //Set gridfs-stream connection
    grid.mongo = db.mongo;
    var gfs = grid(getConnDb());