[英]Create new database with API call
I want to create a new database at the time of the API call. 我想在API调用时创建一个新数据库。 I am already connected to one main database.
我已经连接到一个主数据库。
I have tried using mongoose.connect() method. 我尝试使用mongoose.connect()方法。 And it gives me a positive response.
它给了我积极的回应。 But when I checked in mongo console I did not find the newly created database.
但是当我签入mongo控制台时,我没有找到新创建的数据库。
Here is my code. 这是我的代码。
const connectionString = `mongodb://${process.env.DB_HOST}:${
process.env.DB_PORT
}/client_${Math.random()
.toString(36)
.substring(2, 8)}`;
mongoose.connect(
connectionString,
{
autoReconnect: true,
reconnectTries: 60,
reconnectInterval: 10000,
useNewUrlParser: true,
useCreateIndex: true
},
(error) => {
if (error) {
console.log(error);
} else {
console.log('Connected');
}
}
);
Hope you got my point. 希望你明白我的意思。 Looking for a solution.
寻找解决方案。
As per mongodb documentation: 根据mongodb文档:
If a database does not exist, MongoDB creates the database when you first store data for that database.
如果数据库不存在,则在您第一次为该数据库存储数据时,MongoDB会创建该数据库。 As such, you can switch to a non-existent database and perform the following operation in the mongo shell.
这样,您可以切换到不存在的数据库并在mongo shell中执行以下操作。 link
链接
This is true for mongo-shell as well, if you do use mydb;
如果您确实
use mydb;
,对mongo-shell也是如此use mydb;
to create one and immediately do show dbs;
创建一个并立即
show dbs;
it won't show up unless you create some data for that mydb
like createCollection(), insert() etc
. 除非您为该
mydb
创建一些数据,如createCollection(), insert() etc
否则它不会显示。
So your code is alright because connect()
is as good as use db;
这样您的代码就可以了,因为
connect()
和use db;
一样好use db;
. 。 Unless you create some data for that db you won't see that in mongo console.
除非您为该数据库创建一些数据,否则您不会在mongo控制台中看到该数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.