【问题标题】:How to connect to specific database with Mongoose and node?如何使用 Mongoose 和节点连接到特定数据库?
【发布时间】: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

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

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2018-07-31
      • 1970-01-01
      • 2017-08-12
      • 1970-01-01
      • 1970-01-01
      • 2020-03-26
      • 1970-01-01
      • 2023-03-24
      • 2018-07-22
      相关资源
      最近更新 更多