首页 > 解决方案 > 如何使用 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

如何将此模型与数据库和我需要的集合相关联?

标签: node.jsmongodbmongoose

解决方案


请在 URI 中指定数据库名称,如链接(或)请使用 mongo URI 获取默认客户端对象,然后获取所需的数据库和集合对象。


推荐阅读