我已经找到了一些在shell中列出集合的答案,但我在nodejs脚本中找到列出集合的所有答案似乎都已被弃用,答案collectionNames和moongose.connection.db返回没有方法.
我正在学习如何使用 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();
});
Run Code Online (Sandbox Code Playgroud)
现在想用Mongoose来练习。所以在我的 app.js 中建立连接我这样做:
mongoose.connect(process.env.mongo_connection_string , {useNewUrlParser: true})
.then( () => console.log("Connection established"))
.catch(err => console.log(err))
Run Code Online (Sandbox Code Playgroud)
然后,我为要存储在数据库中的对象之一创建了一个架构。
const mongoose = require('mongoose')
const UserSchema = new mongoose.Schema({
name: {
type: String, …Run Code Online (Sandbox Code Playgroud) 有一些类似的问题,但所有这些问题都涉及使用MongoDB NodeJS驱动程序而不是Mongoose ODM.
我阅读了文档,但找不到这样的功能.