简体   繁体   English

是否可以使用 ZCCADCDEDB567ABAE643E15DCF0974E503Z 在 MongoDB 中创建新数据库?

[英]Is it possible to create a new database in MongoDB with Mongoose?

I am trying to figure out if I can create a new database in MongoDB with Mongoose.我想弄清楚是否可以使用 Mongoose 在 MongoDB 中创建一个新数据库。 I am running on Node, and I know the MongoDB driver for Node can do it, but I am wondering if I can do it just from Mongoose.我在 Node 上运行,我知道 Node 的 MongoDB 驱动程序可以做到这一点,但我想知道我是否可以仅从 Mongoose 做到这一点。

Is there an equivalent to the db.createCollection(name, options) from the Node MongoDB driver in Mongoose? Mongoose 中的节点 MongoDB 驱动程序中的db.createCollection(name, options)是否有等效项? My google skills are failing right now.我的谷歌技能现在失败了。

I just was trying to figure out if I had to install the whole MongoDB driver just for that, but I think I do.我只是想弄清楚是否必须为此安装整个 MongoDB 驱动程序,但我想我需要。

Yes, you can specify the database name in your connection string.是的,您可以在连接字符串中指定数据库名称。

db = mongoose.connect('mongodb://localhost/dbname1')

As soon as you create a record with that connection, it will create the new database and collections under the database name of 'dbname1'.一旦您使用该连接创建记录,它就会在“dbname1”的数据库名称下创建新的数据库和集合。 If you wanted to create a new database, you can specify a different connection string:如果要创建新数据库,可以指定不同的连接字符串:

db = mongoose.connect('mongodb://localhost/dbname2')

and that will create all your records under the name 'dbname2'.这将创建名为“dbname2”的所有记录。 Your documents will not import over to dbname2, you will have to do an import of those records if you wanted to do that.您的文档不会导入到 dbname2,如果您想这样做,您必须导入这些记录。 Hope that helps.希望有帮助。

If you want to create database for online cluster you also need to enter your database name when you pass the uri like:-如果您想为在线集群创建数据库,您还需要在传递 uri 时输入数据库名称,例如:-

"mongodb+srv://<Username>:<Password>@resumeapp.3ditras.mongodb.net/<DatabaseName>?retryWrites=true&w=majority"

Just Try this code it's very simple and clean试试这个代码,它非常简单和干净

const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/yourdatabasename').then(() => console.log('Connected to MongoDB...')).catch((err) => console.error("Coudn't connect MongoDB....", err));

const customerSchema= new mongoose.Schema({ name: String,address: String,email:String,});

const Customer= mongoose.model('Customer',courseSchema);

async function createNewCustomer() {const customer= new Customer({name: 'new customer',address: 'new address',email: 'customer1@new.com',});const result = await customer.save();console.log(result);
}
createNewCustomer();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM