node.js - 如何使用 Mongoose 和节点连接到特定数据库?
问题描述
我正在学习如何使用 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();
});
现在想用Mongoose来练习。所以在我的 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
如何将此模型与数据库和我需要的集合相关联?
解决方案
请在 URI 中指定数据库名称,如链接(或)请使用 mongo URI 获取默认客户端对象,然后获取所需的数据库和集合对象。
推荐阅读
- unity3d - 网格变换不会相应地转换为 WheelCollider
- swift - 使用 NavigationLink 推送视图时,已发布的 ViewModel 会导致内存泄漏
- java - 如何计算 Java 批处理中捕获的异常数量?
- java - Android:错误:找不到符号包。添加(新 MyAppPackage())
- vba - 有没有办法“按原样”检索与 PowerPoint 演示文稿中的图片相对应的内部存储的 EMF 文件?
- java - Spring JPA 停止关系创建新表
- python - Django inspectdb 省略了整数主键
- python - 在 Python 上无法正常运行的操作顺序。有谁知道发生了什么?
- netlogo - 报告行为空间 Netlogo 中的列表
- php - 生成允许访客将文件上传到服务器的唯一 URL