blizzer
blizzer

Reputation: 29

CouchDB Database create/delete

I have a NodeJS application and I have a problem using nano to create/delete a database. I want to check if there is a database with the users name. If there is a database I would like to clear it so I destroy it and create a new one.

module.exports.createDB = function () {
  try {
    nano.db.list().then((body) => {
      // body is an array
      body.forEach((db) => {
        if(db == getUser.username){
          nano.db.destroy(getUser.username)
        }
      });
    });
    nano.db.create(getUser.username).then((body) => {
      nano.use(getUser.username).insert(
        { "views": 
          { "webview": 
            { "map": "function (doc) {\n  emit(doc.msg, 1);\n}", "reduce": "_count" }
          }
        }, '_design/output', function (error, response) {
          console.log("Design Created");
        });
    })
  } catch (error) {
    console.log(error);
  }
}

If there is no database with this name it works fine but if there is a database with the same name i get the error:

(node:33354) UnhandledPromiseRejectionWarning: Error: The database could not be created, the file already exists.

But I don't know why because I destroy this database before?

Upvotes: 0

Views: 756

Answers (1)

Glynn Bird
Glynn Bird

Reputation: 5637

You can check whether a database exists by calling db.info(). If it exists, you can then destroy it and re-create it. If it doesn't exist, just create it:

const Nano = require('nano')
const nano = Nano(process.env.COUCH_URL)

const main = async () => {

  const DBNAME = 'mydb'
  const db = nano.db.use(DBNAME)
  try {
    const info = await db.info()
    console.log('DB Exists!', info)
    await nano.db.destroy(DBNAME)
  } catch (e) {
    console.log('DB does not exist!')
  }
  await nano.db.create(DBNAME)
}

main()

Upvotes: 1

Related Questions