How to perform Update and Delete operations in a bucket using Couchbase and Nodejs sdk

有些话、适合烂在心里 提交于 2019-12-12 05:01:41

问题


I am moving from mongodb to Couchbase using Node.js. I want to perform the CRUD operations. Insert(create) and Get are working fine, but when I want to perform Update and Delete getting some error messages (Here update purpose using 'upsert','replace' are used) like:

TypeError: Cannot read property 'replace' of undefined

Here is code:

db.js

// Instantiate Couchbase and Ottoman
var couchbase=require('couchbase');
var ottoman=require('ottoman');
// Build my cluster object and open a new cluster
var myCluster = new couchbase.Cluster('localhost:8091');
var myBucket = myCluster.openBucket('default');
ottoman.bucket=myBucket;
require('./model/user');
ottoman.ensureIndices(function(){});

user.js

var db = require('./../db.js').myBucket;
var ottoman = require('ottoman');

var userMdl = ottoman.model('User', {
    firstName: {type:'string'},
    lastName: {type:'string'},
    created: {type: 'Date', default:function(){return new Date()}},
    email:'string',
    phone: 'string'
},{
    index: {
        findByID: {   
            by: '_id'
        },
    }

})  
module.exports = userMdl;

routes.js

 var bodyParser = require('body-parser');
    var db = require('../schema/db').myBucket;
    var user=require('../schema/model/user');
    var jsonParser = bodyParser.json();
    var urlencodedParser = bodyParser.urlencoded({ extended: false });

    module.exports = function (app) {
    // Delete a record
    app.post("/api/delete/:_id", function(req, res) {
        console.log("_id:"+req.params._id)
        if(!req.params._id) {
            return res.status(400).send({"status": "error", "message": "A document id is required"});
        }
        db.delete({_id:req.params._id}, function(error, result) {
            if(error) {
                return res.status(400).send(error);
            }
            res.send(result);
        });
    });

    app.post('/api/user/update/:id',function(req,res){
       db.replace(req.params.id,{firstName:"Mahesh"},function(err,result){
         if (err) {
            res.status = 400;
            res.send(err);
            return;
         }
         else {
           res.status = 202;
           res.send(result);  
          }
        })
      })
    }

I am stuck here from last two days.


回答1:


You missed one argument although it can be optional.
From Couchbase Node.js SDK document, it have 4 arguments, but you have only 3.

db.replace(req.params.id,{firstName:"Mahesh"},function(err,result){
=>
db.replace(req.params.id,{firstName:"Mahesh"}, {}, function(err,result){

With 3rd argument of empty map may work properly, but notice that Couchbase uses optimistic locking, so you require "CAS" value for original document when you modify the original to get data integrity.




回答2:


the line in db.js var ottoman = require('ottoman');it's a constructor itself. Then you have two instances, and the error comes in user.js when you try to define a model, because node-ottoman needs a reference to the bucket.

You should assign the bucket in the user.js or reuse the ottoman object that you left in the db.js

model.js

    // Instantiate Couchbase and Ottoman

    var couchbase = require('couchbase');
    var ottoman = require('ottoman');

    // Build my cluster object and open a new cluster
    var myCluster = new couchbase.Cluster('localhost:8091');
    var myBucket = myCluster.openBucket('default');
    ottoman.bucket = myBucket;

    var userMdl = ottoman.model('User', {
        firstName: {type:'string'},
        lastName: {type:'string'},
        created: {type: 'Date', default:function(){return new Date()}},
        email:'string',
        phone: 'string'
    },{
        index: {
            findByID: {   
                by: '_id'
            },
        }

    }) ;

    // this line needs to be after you define the model
    ottoman.ensureIndices(function(){});

    module.exports = userMdl;
    model.exports = mybucket;



回答3:


You can update Couchbase document using 2 ways 1st by upsert method and second by N1qlQuery

bucket.upsert('user', {'name': 'Jay'}, {'expiry': 1}, function(err){
    bucket.get('user', function(err, result) {
        console.log('Have item: %j', result.value);
    })
});

let query = N1qlQuery.fromString("UPDATE `"+BUCKETNAME+"` SET name='"+data.name+"'  where _id ='"+id+"'");
bucket.query(query,(error,result)=>{
    if(error){
        console.log(error);
    }
    console.log(result);
});

You can delete Couchbase document using 2 ways 1st is removed method and second by N1qlQuery

bucket.remove(id, function(error, result) {
    console.log("Deleted");
});

let query = N1qlQuery.fromString("DELETE FROM `"+BUCKETNAME+"` WHERE _id = '"+id+"'");
bucket.query(query,(error,result)=>{
    if(error){
        console.log(error);
    }
    console.log(result);
})


来源:https://stackoverflow.com/questions/35792929/how-to-perform-update-and-delete-operations-in-a-bucket-using-couchbase-and-node

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!