how to do update operation in express.js - node.js

I have a simple student database program in express.js using mongodb.How can the updation operation be performed for the following program:
my app.js programs is as follows:
var studentDb=new StudentDb('localhost',27017);
app.get('/',function(req,res){
studentDb.findAll(function(error,stu){
res.end(JSON.stringify({
title:'students',
students:stu
}));
});
});
app.get('/student/new',function(req,res)
{
var rollno=req.param('rollno');
studentDb.findByrollno(rollno,function(error,docs)
{
if( error ) { res.end(JSON.stringify(error)); }else{
if(docs.length==1)
{res.end('already has one.');}
else
{ studentDb.save({
title:req.param('title'),
name:req.param('name'),
rollno:req.param('rollno')
},
function(error,docs)
{
console.log(docs);
});setTimeout(function(){ res.redirect('/');},5000);}}
});
});
app.delete('/student/new', function (req, res) {
studentDb.findByrollno(req.param('rollno'), function (error, docs) {
studentDb.delete(req.param('rollno'),function (error,students) {
if (error) {
console.log(error);
} else {
console.log("deleted rollno: " + req.param('rollno'));
} res.end(JSON.stringify(students));
});
});
});
here is my studentdb.js file
var Db = require('mongodb').Db;
var Connection = require('mongodb').Connection;
var Server = require('mongodb').Server;
var JSON = require('mongodb').JSON;
var ObjectID = require('mongodb').ObjectID;
StudentDb = function(host, port) {
this.db= new Db('studentdata', new Server(host, port, {safe: false}, {auto_reconnect: true}, {}));
this.db.open(function(){});
};
StudentDb.prototype.getCollection= function(callback) {
this.db.collection('students', function(error, student_collection) {
if( error ) callback(error);
else callback(null, student_collection);
});
};
StudentDb.prototype.findAll = function(callback) {
this.getCollection(function(error, student_collection) {
if( error ) callback(error)
else {
student_collection.find().toArray(function(error, results) {
if( error ) callback(error)
else callback(null, results)
});
}
});
};
StudentDb.prototype.findByrollno = function(rollno,callback) {
this.getCollection(function(error, student_collection) {
if( error ) callback(error)
else {
student_collection.find({rollno:rollno}).toArray(function(error, results) {
if( error ) callback(error)
else callback(null, results)
});
}
});
};
StudentDb.prototype.save = function(students, callback) {
this.getCollection(function(error, student_collection) {
if( error ) callback(error)
else {
if( typeof(students.length)=="undefined")
students = [students];
for( var i =0;i< students.length;i++ ) {
student = students[i];
student.created_at = new Date();
}
student_collection.insert(students, function() {
callback(null, students);
});
}
});
};
StudentDb.prototype.delete = function(rollno,callback) {
this.getCollection(function(error, student_collection) {
if( error ) callback(error)
else {
student_collection.remove({rollno:rollno},function(error, results) {
if( error ) callback(error)
else callback(null, results)
});
}
});
};
i need to update a field in the student database.but i am unaware of using the update query.pls help me.

You mean you don't know how to implement a StudentDb.update method? You just need to make an object using Mongo's update operators. There are good docs on how to use these here. This method will update one student setting any fields you set in the updatedFields object in the student:
// updatedFields should be an object with fields to set on the student
// e.g. updatedFields = {name: "Bob", favouriteSubject: "Computing"}
StudentDb.prototype.update = function(rollno, updatedFields, callback) {
this.getCollection(function(error, student_collection) {
if( error ) callback(error)
else {
student_collection.updateOne(
{rollno: rollno},
{$set: updatedFields},
callback
);
}
});
};
Note that since your callbacks follow the callback(err, result) convention there's no need to call them yourself you can pass them to Mongo to call them for you.

From the MongoDb docs:
db.collection.update(
<query>,
<update>,
{
upsert: <boolean>,
multi: <boolean>,
writeConcern: <document>
}
)
Source: MongoD docs
You can create a new method on your StudentDb object prototype for handling update operations:
StudentDb.prototype.update = function (rollno, updatedFields, callback) {
this.getCollection(function(error, student_collection) {
if( error ) callback(error);
else {
student_collection.update({rollno: rollno}, updatedFields, function (err, updatedStudent) {
if (err) callback(err);
else callback(null, updatedStudent);
});
}
Add a new handler to your router using the PUT HTTP verb:
app.put('/student/new', function (req, res) {
studentDb.update(req.param('rollno'), req.body, function (err, student){
if (err) {
console.error(err);
} else {
res.send(JSON.stringify(student));
}
});
});
As a sidenote, you can check out the mongoose module for nodejs, working directly with the MongoDB native driver is a bit more verbose.
Also seeing that you are fairly new to nodejs, I suggest reading a bit more about RESTful services, the 'Content-Type' HTTP header and send your data in JSON format.
Improve your error handling when responding to HTTP requests (e.g. if the update operation fails, let the client know about it):
studentDb.update(req.param('rollno'), req.body, function (err, student){
if (err) {
console.error(err);
res.status(500).json(err); // respond with HTTP status 500 (internal server error)
} else {
console.log("updated rollno: " + req.param('rollno'));
} res.send(JSON.stringify(student));
});

Related

Botpress - how to bring database values into the chat window?

I'm trying to build a chatbot using Botpress. I'm a beginner, looking for your help. One of the requirements is to query database to answer questions. This is what I have tried so far:
dbconnect.js
var oracledb = require('oracledb');
var dbConfig = require('./dbconfig.js');
var db = function dbCall(sql, values) {
return new Promise(function(resolve, reject){
oracledb.getConnection(
{
user : dbConfig.user,
password : dbConfig.password,
connectString : dbConfig.connectString
},
function(err, connection) {
if (err) {
reject(err);
return;
}
connection.execute(
sql,
values,
{
maxRows: 1
},
function(err, result) {
if (err) {
console.error(err.message);
return;
}
resolve(result);
doRelease(connection);
}
);
});
});
}
// Note: connections should always be released when not needed
function doRelease(connection) {
connection.close(
function (err) {
if (err) {
console.error(err.message);
}
});
}
module.exports = db;
select.js
var dbConnect = require('../oracledb/dbconnect');
dbConnect('select code from table1' +
' where id=:id', {id:'value1'}).then(function (response) {
console.info(response.rows);
}).catch(function(error) {
console.info(error);
});
everything above works great, if I run select.js. How could I bring the response into the botpress chat window? I tried placing the select.js code in index.js event.reply, it doesn't work.
Thanks,
Babu.
I have resolved this by using the promise directly in the action.
return dbConnect('<SQL here>=:id', { id: Id })
.then(function(response) {
var res = response.rows
console.info(res);
const newState = { ...state, status: res}
return newState
})
.catch(function(error) {
console.info(error)
})
Note that response has the resultset.

i am not getting any idea that where is error occured node js callback not function

in this function we get id from Mongo Database and process function to put varriable in GetID varriable
"callback is not function"
var GetID = function( nameval , callback ){
console.log(nameval);
console.log("munesh hello");
var result = GenerateID.find({ "id_name" : nameval },{"id_code":1 , "id_value":1 , "_id":0},function( err , genvalue ) {
if ( err )
{
console.log('error has been occured');
//throw err;
}
else {
if(genvalue === null)
{
callback( err , false );
}
else
{
console.log(genvalue);
//calling this function
callback( err , true );
}
}
// console.log(genvalue);
});
console.log('munesh kumar');
// console.log(result);
console.log('kumar');
};
When calling GetID, you are not sending 2 parameters (nameval and callback). You are only sending the first parameter:
var region_id = GenerateID.GetID( name );
Instead this is how you should call the function:
GenerateID.GetID(name, function(error, result) {
if(error) {
// handle error
} else {
if(!result) {
// not found
} else {
// do something with result
}
}
});
Remember that you are dealing with asynchronous functions. You cannot return output directly from an asynchronous function (GetID). Instead you have to pass it to the callback function.
Your GetID function should be something like this:
var GetID = function(nameval, callback) {
GenerateID
.find({ "id_name": nameval }, { "id_code": 1, "id_value": 1, "_id": 0 }, function(err, genvalue) {
if (err) {
callback(err);
} else {
if (genvalue === null) {
callback(null, null); // no document found
} else {
callback(null, genvalue);
}
}
});
};
var region_id = GenerateID.GetID( name , function(error, result) {
if(error) {
// handle error
console.log("getting any error");
} else {
console.log(region_id);
if(!result) {
console.log('data is not coming');
} else {
console.log('data is coming');
}
}
});
get id function are below var GetID =function( nameval ,callback){
console.log(nameval);
console.log("munesh hello");
GenerateID.find({ "id_name" : nameval },{"id_code":1 , "id_value":1 , "_id":0},function( err , genvalue ) {
if (err) {
console.log('hello');
// callback(err);
} else {
if (genvalue === null) {
console.log('123');
callback(null, null); // no document found
} else {
console.log('456');
callback(null, genvalue);
}
}
});
};

I need help about Asynchronus call in node.js with Mongodb, i need to call synchronous method for further processing of data

calling id from mongodb with callback function
var GetID = function (nameval, callback) {
console.log(nameval);
console.log("munesh hello");
GenerateID.find({ "id_name": nameval }, {
"id_code": 1,
"id_value": 1, "_id": 0
}, function (err, genvalue) {
if (err) {
console.log('hello');
}
else {
if (genvalue === null) {
callback(err, false);
}
else {
callback(err, true);
}
}
console.log(genvalue);
});
};
and calling above method so we need
so we need id from GenerateID.GetID and do our own work.
var region_id = GenerateID.GetID(name, function (error, result) {
if (error) {
console.log("getting any error");
} else {
console.log(region_id);
if (!result) {
console.log('data is not coming');
} else {
console.log('data is coming');
}
}
});
You have a number of issues. In the first piece of code, you need to pass the actual value when calling the callback.
In the second, you need to set region_id = result.
Ideally you would do this using promises as demonstrated below.
var GetID = function(nameval){
return new Promise((resolve,reject) => {
console.log(nameval);
console.log("munesh hello");
GenerateId.find({ "id_name" : nameval },{"id_code":1 , "id_value":1, "_id":0},
function( err , genvalue ) {
console.log(genvalue);
if (err) {
console.log('hello');
return reject()
}
if (genvalue == null) { return resolve(false); }
return resolve(genValue);
});
});
}
var GetIDPromise = GenerateId.GetID(name);
GetIDPromise.then(
genValue => {
if ( genValue == false ){
console.log('data is not coming');
// handle region id not being available. Perhaps return and show an error
}else{
var region_id = genValue;
// continue execution and use region id.
}
},
error => {
console.log("getting any error");
}
)

Node js mongoerror 'write ECONNRESET'

When creating new document in node js gives MongoError of write ECONNRESET.
Following is the error in console when creating the new document:
error: Error adding new agreementTemplate ! Error :
{"name":"MongoError","message":"write ECONNRESET"}
following is the controller function creating the error.
function addSubChapter(req, res) {
logger.debug('Processing request for creating a new agreement.');
console.log(req.body);
async.waterfall([
function (callback) {
agreementService.getAgreementTemplate( callback);
},
function (data, callback) {
agreementTmplService.AgreementTemplateSetDefaultFalse(function(err, result){
callback(null, data);
});
},
function (data, callback) {
var agreementTemplate =data.result[0];
var chapter ={
name: req.body.name
}
agreementTemplate = agreementTemplate.toObject(); // swap for a plain javascript object instance
delete agreementTemplate["_id"];
agreementTemplate.createdBy= req.body.user;
agreementTemplate.created= new Date();
//agreementTemplate.Chapters.push(chapter);
var chapters = agreementTemplate.Chapters;
for(var i=0;i<chapters.length; i++){
if(chapters[i].name == req.body.chapter){
var subChap ={
name: req.body.name
}
chapters[i].subChapters.push(subChap);
}
}
console.log('----------------------');
console.log(agreementTemplate);
agreementService.createAgreementTemplate(agreementTemplate, callback);
},
function (data, callback) {
agreementTmplService.addSubChapter(req.body, callback);
}
], function (err, result) {
utils.processResponse(err, result, res);
});
}
When creating the agreement template it causes the error, here is the service function:
function createAgreementTemplate(data, callback) {
serviceHelper.createModel(AgreementTemplate, 'agreementTemplate', data, callback);
}
and the createModel function is as follows.
function createModel(model, modelName, modelData, callback) {
logger.debug('Creating new Model : %s', modelName);
var modelObj = model(modelData);
modelObj.save(function (err, newModelObj) {
if (err) {
logger.error('Error adding new %s ! Error : %s', modelName, JSON.stringify(err));
callback(utils.handleMongodbError(err), null);
} else {
logger.info('New Model of type : %s created with id : %s', modelName, JSON.stringify(newModelObj._id));
var result = {};
result.status = httpStatus.OK;
result.result = newModelObj._id;
callback(null, result);
}
});
}

PUT method in Node.js/MongoDB

I'm having issues with a simple PUT method in Node.js (MongoDB collection.update). Any help would be appreciated. At this point, I'm not getting an error, just an empty response.
index.js:
app.put('/UpdateValues/:collection/:entity', function(req, res) {
var params = req.params;
var entity = params.entity;
var collection = params.collection;
var value1 = req.body.value1;
var value2 = req.body.value2;
if (entity) {
collectionDriver.updateValues(collection, entity, value1, value2, function(error, objs) {
if (error) { res.status(400).send(error); }
else { res.status(200).send(objs); }
});
} else {
res.send(400, {error: 'bad url', url: req.url});
}
});
collectionDriver.js:
CollectionDriver.prototype.updateValues = function(collectionName, nameDoc, value1new, value2new, callback) {
this.getCollection(collectionName, function(error, the_collection) {
if (error) callback(error);
else {
the_collection.update(
{ name: nameDoc },
{ $set: {
value1: value1new,
value2: value2new
}},
function( err, result ) {
if ( err ) throw err;
}
);
}
});
};
Testing with:
$ curl -i -X PUT -H 'Content-Type: application/json' -d '{"value1":"1","value2":"1"}' http://localhost/UpdateValues/collection/test
Reference the callback you are passing in within your function. Presently you do not. You also seem like you are expeting the modified document in response, so you need .findOneAndUpdate() instead:
CollectionDriver.prototype.updateValues = function(collectionName, nameDoc, value1new, value2new, callback) {
this.getCollection(collectionName, function(error, the_collection) {
if (error) callback(error);
the_collection.findOneAndUpdate( // <-- new method
{ name: nameDoc },
{ $set: {
value1: value1new,
value2: value2new
}},
{ returnOriginal: false }, // <-- tells to return modified document
callback // <--- passes to callback you passed in
);
});
});

Resources