简体   繁体   中英

How to check and create databases in CouchDB with Node.JS?

I'm trying to create a small web application and I have an issue. In my code, I initialize my database name in the beginning and before my application executes and I'd like to check if the database name exists on the server and if not create a database with that name. So in other words, I'm trying to do something like this;

if(dbName is not exists){
couch.createDatabase(dbName).then(function(){
     console.log('Database created');
 };
}

But I'm not sure how to do this properly. I'm trying to learn and use npm node-couchdb package and I'd be grateful if you can help me to solve this issue without using any other package.

Update: Now I can check if the database exist with couch.listDatabases() and if not create a new one with couch.createDatabase with following;

couch.listDatabases().then(function(dbs){
var controller = 0;
console.log(dbs);
for(var i= 0; i <= dbs.length; i++){
    if(dbName == dbs[i]){
        controller += 1;
    }
}
if(controller == 0){
    couch.createDatabase(dbName).then(function(){
     console.log('Database created');
 },
 function(err){
     res.send(err);
 });
}
});

I can see the new database on the server, but when I try to reach it with my application I get this error;

{"code":"EDOCMISSING","body":{"error":"not_found","reason":"missing"}}

you can get the list of the databases like this:

couch.listDatabases()
.then(
   dbs => dbs.map(...), 
   err => {
   // request error occured 
});

and check if your db already exist or not.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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