![](/img/trans.png)
[英]How to get access to the mongo db in node using mongo client outside the call back
[英]Access mongo db from shell which is created using node application
嗨,我是 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;
我的架構 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
它與此數據庫連接而沒有任何錯誤。 當我嘗試訪問數據時,它沒有顯示任何數據。我檢查哪些所有數據庫都可用。 它顯示默認測試數據庫。
您的連接字符串中缺少數據庫。
嘗試類似:
const connect = async () => {
await mongoose.connect('mongodb://localhost/my-database')
}
我猜 mongoose 在連接字符串未指定要使用的任何數據庫時使用default
作為默認值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.