如何从mongoose中获取mongodb版本

9

使用Mongo CLI非常简单:

db.version ()

我该如何使用mongoose实现相同的功能?我该如何发送自定义命令?
3个回答

16
你可以通过Mongoose连接使用本机Mongo驱动程序的 Admin#buildInfo 方法进行操作。
var mongoose = require('mongoose');

mongoose.connect('mongodb://localhost/test', function(err){
  var admin = new mongoose.mongo.Admin(mongoose.connection.db);
  admin.buildInfo(function (err, info) {
     console.log(info.version);
  });
});

只是一条注释,如果您没有使用mongodb模块,您需要指向require("mongoose/node_modules/mongodb") - Gabriel Llamas
2
mongoose使用的mongodb模块可以通过require('mongoose').mongo来访问。http://mongoosejs.com/docs/api.html#index_Mongoose-mongo - aaronheckmann
这似乎在mongoose 7中不再起作用了。 - boly38

5

1

试试这个,它会给你MongoDB和Mongoose的版本

async function run() {
    var admin = new mongoose.mongo.Admin(mongoose.connection.db);
    admin.buildInfo(function (err, info) {
       console.log(`mongodb: ${info.version}`);
       console.log(`mongoose: ${mongoose.version}`);
    });
}

mongoose.connect(process.env.MONGO_URI, {
        useNewUrlParser: true,
        useUnifiedTopology: true
    })
    .then(() => {
        console.log('MongoDB connected');
        run();
    })
    .catch(error => {
        console.log(error);
    });

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接