node.jscloudant

How to migrate from Mamp DB to Cloudant DB in Node.js application


I am new in Cloudant db. I need to migrate from Mamp db to Cloudant. I am getting form data and inserting it to DB but with Cloudant I am not able to understand insert command as it work differently (Object base save). How can I make a Db connection?

The insert code is given below:

const mysql = require("mysql");
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');
const { promisify } = require ('util');

// const db = mysql.createConnection({
//     host: process.env.DATABASE_HOST,
//     port: process.env.DATABASE_PORT,
//     user: process.env.DATABASE_USER,
//     password: process.env.DATABSE_PASSWORD,
//     database: process.env.DATABASE
// });
Cloudant = require('@cloudant/cloudant');    
    cloudAntConfig = {
      url: process.env.CLOUD_ANT_URL,
      apiKey: {iamauth: {iamApiKey: process.env.CLOUD_ANT_APIKEY}},
      database: process.env.CLOUD_ANT_DB
      };
exports.assessment = (req,res) => {
    console.log(req.body);
    // console.log(user.User_ID );
    const { TeamName, question1, question2, question3, question4, question5, question6, question7, question8, question9, question10, question11, question12, question13, question14, question15, question16, question17, question18, question19, question20, question21, question22, question23, question24, question25, question26, question27, question28, question29, question30, question31, question32, question33, question34, question35 } = req.body;
    // console.log(parseInt(question3)+parseInt(question4));
    // some code about data goes here
    db.query('INSERT INTO assessment_result SET ?',{User_Id : 1,Team_Name : TeamName, Dimension_1_Score  : (dime_1_total/25)*100, Dimension_2_Score  : (dime_2_total/50)*100, Dimension_3_Score  : (dime_3_total/50)*100, Dimension_4_Score  : (dime_4_total/50)*100, Total_Score  : final_total, Total_Score_Persentage  : (final_total/175)*100 },(error,results)=>{
        // res.render('register');
        })
}


Solution

  • The Getting Started section of the @cloudant/cloudant README shows how to insert a document into a Cloudant database.

    const Cloudant = require('@cloudant/cloudant');    
    cloudAntConfig = {
      url: process.env.CLOUD_ANT_URL,
      plugins: { iamauth: { iamApiKey: process.env.CLOUD_ANT_APIKEY } }
    }
    const cloudant = Cloudant(cloudAntConfig);
    const db = cloudant.use(process.env.CLOUD_ANT_DB)
    // ...
    db.insert({User_Id: 1, /* etc the rest of your document content */}, (err, data) => {})
    

    Probably worth noting though that @cloudant/cloudant is deprecated and if you are writing new code you should consider using @ibm-cloud/cloudant.