【发布时间】:2019-12-11 17:10:20
【问题描述】:
我正在学习如何使用 Mongoose,但有一些我不明白的地方 - 如何连接到集群中的特定数据库和集合?
我有 5 个不同的数据库,每个数据库都有几个不同的集合
当我使用纯 Mongo 客户端时——官方文档中显示的方式,我是这样连接的:
const MongoClient = require('mongodb').MongoClient;
const uri = process.env.mongo_connection_string;
const client = new MongoClient(uri, { useNewUrlParser: true });
client.connect(err => {
const collection = client.db("database_name").collection("collection_name");
// Do some work here in the selected database and the selected collection
client.close();
});
现在我想用猫鼬来练习。所以在我的 app.js 中建立我的连接:
mongoose.connect(process.env.mongo_connection_string , {useNewUrlParser: true})
.then( () => console.log("Connection established"))
.catch(err => console.log(err))
然后,我为要存储在数据库中的其中一个对象创建了一个模式。
const mongoose = require('mongoose')
const UserSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
email: {
type: String,
required: true
}
})
const User = mongoose.model('User', UserSchema)
module.exports = User
如何将此模型与我需要的数据库和集合相关联?
【问题讨论】: