从使用节点应用程序创建的shell访问mongo db

问题描述 投票:0回答:1

嗨,我是Node和mongo DB开发的新手。我创建了一个简单的节点应用程序。我正在使用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;

我的模式类看起来像

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 

它与此数据库连接,没有任何错误。尝试访问数据时未显示任何数据。我检查所有数据库均可用。它显示默认的测试数据库。

node.js database mongodb mongo-shell
1个回答
0
投票

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

尝试类似的东西:

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

我猜想当连接字符串未指定要使用的任何数据库时,猫鼬默认使用default

© www.soinside.com 2019 - 2024. All rights reserved.