从使用节点应用程序创建的 shell 访问 mongo 数据库

Access mongo db from shell which is created using node application

嗨,我是节点和 mongo 数据库开发的新手。我创建了一个简单的节点应用程序。我正在使用 mongoDB。我已经初始化了 mondo db 并且能够插入一些数据。在我的 app.js 中,我添加了数据库连接,如下所示:

const mongoose = require('mongoose');
const mongoDB = 'mongodb://localhost:27017';
mongoose.connect(mongoDB);
mongoose.Promise = global.Promise;
const db = mongoose.connection;

我的架构 class 看起来像

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

let UserSchema = new Schema({
    // publisherId: {type: String, required: true},
    userName: {type: String, required: true},
    age: {type: Number, required: true}
},{timestamps: true });


// Export the model
module.exports = mongoose.model('User', UserSchema);

现在我想从命令行访问相同的数据,所以我尝试连接我的数据库。

mongo mongodb://localhost:27017 

它与这个数据库的连接没有任何错误。当我尝试访问数据时,它没有显示任何 data.I 检查哪些数据库可用。它显示默认测试数据库。

您的连接字符串中缺少数据库。

试试这样的东西:

const connect = async () => {
  await mongoose.connect('mongodb://localhost/my-database')
}

我猜 mongoose 在连接字符串未指定要使用的任何数据库时默认使用 default