res.json() is not a function...mongoose - node.js

I am not sure where i went wrong,when i run the code,it says error res.json(res) is not a function......
my node.js,
exports.inserttopic = function (req, res) {
var topics = new Topics(req.body);console.log(topics)
topics.status = '1';
topics.type = 'topics';
var data = {};
topics.save(function (err, res) {
if (err) {
console.log(err);
return err;
}
data = { status: false, error_code: 1, message: 'Unable to insert' };
if (res) {
data = { status: true, error_code: 0, result: res, message: 'Inserted successfully' };
}
res.json(data);
});
};

Use a different variable name when you do topics.save() than res. In your code, you are overwriting the original res and thus do not have access to the response object.
So this is what your code would look like
exports.inserttopic = function (req, res) {
var topics = new Topics(req.body);console.log(topics)
topics.status = '1';
topics.type = 'topics';
var data = {};
topics.save(function (err, mongooseResponse) { \\ Do not use res here
if (err) {
console.log(err);
return err;
}
data = { status: false, error_code: 1, message: 'Unable to insert' };
if (mongooseResponse) {
data = { status: true, error_code: 0, result: mongooseResponse, message: 'Inserted successfully' };
}
res.json(data);
});
};

Related

Async handling issue in nodejs

I am new in nodejs. I am creating a basic API to get record by id. Everything is working fine. It is returning user data from database. But when i use password variable from response in same function it give me empty value whereas i am getting value in response. I think this is async issue but i dont know how to fix it.
This is API code
var express = require('express');
var db = require('../db/database');
var bcrypt = require('bcrypt');
const router = express.Router();
router.get("/:userId", (req, res, next) => {
let uid = req.params.userId;
db.query(`SELECT * FROM users WHERE u_id = ${uid}`, (err, data)=> {
if(!err) {
if(data && data.length > 0) {
var message = '';
if(data.u_password){
//var pass = data.u_password;
if(bcrypt.compare('123456', data.u_password)) {
// Passwords match
message = 'Passwords match';
} else {
// Passwords don't match
message = 'Passwords dont match';
}
}
res.status(200).json({
message:message,
});
} else {
res.status(200).json({
message:"User Not found."
});
}
}
});
});
database.js
var mysql = require('mysql');
const pool = mysql.createPool({
connectionLimit : 10,
host: 'localhost',
user: 'root',
password: '',
database: 'lost_and_found',
debug : false
});
function executeQuery(sql, callback) {
pool.getConnection((err,connection) => {
if(err) {
return callback(err, null);
} else {
if(connection) {
connection.query(sql, function (error, results, fields) {
connection.release();
if (error) {
return callback(error, null);
}
return callback(null, results);
});
}
}
});
}
function query(sql, callback) {
executeQuery(sql,function(err, data) {
if(err) {
return callback(err);
}
callback(null, data);
});
}
module.exports = {
query: query
}
Response
{"message":""}
Please change the bcrypt.compare code to following code. It is a callback function:
bcrypt.compare('123456', data.u_password, function(err, result) {
if (err) {
// Passwords don't match
message = 'Passwords dont match';
} else {
// Passwords match
message = 'Passwords match';
}
res.status(200).json({
message:message,
});
})
EDIT 1: Please update the method to following logic:
db.query(`SELECT * FROM users WHERE u_id = ${uid}`, (err, data) => {
if (err) {
throw err;
}
if (data && data.length > 0) {
var message = '';
if (data.u_password) {
bcrypt.compare('123456', data.u_password, function (err, result) {
if (err) {
// Passwords don't match
message = 'Passwords dont match';
} else {
// Passwords match
message = 'Passwords match';
}
res.status(200).json({
message: message,
});
})
}
res.status(200).json({
message: "User Not found."
});
}
res.status(200).json({
message: "User Not found."
});
});

MongoDB Update field data

How can i used db.findAndUpdate table user and change my balance from previous amount to newer?
i have try to get balance and the result it show nothing, now i'm confuse to write in findAndUpdate. here's my code:
api:
app.post('/api/account/transfer', (req, res, next) => {
const { body } = req;
const {
sender,
receiver,
amount,
user,
balance,
} = body;
if (!sender) {
return res.send({
success: false,
message: 'Error: Sender cannot be blank!'
});
}
if (!receiver) {
return res.send({
success: false,
message: 'Error: Receiver cannot be blank!'
});
}
if (!amount) {
return res.send({
success: false,
message: 'Error: Fill Amount!'
});
} else if(balance < amount || balance == 0) {
return res.send({
success: false,
message: 'Insufficient funds!'
});
}
//save the new transaction
const newTransaction = new Transaction();
newTransaction.sender = sender;
newTransaction.receiver = receiver;
newTransaction.amount = amount;
newTransaction.save( (err, transaction) => {
if(err) {
return res.send({
success: false,
message: 'Error: Server error.'
});
}else{
return res.send({
success: true,
message: 'Transfer Success!'
});
}
});
//update user balance
User.findOneAndUpdate({
});
and here's the screenshoot:
so what i want is, if i'm as a receiver my balance will be increase.
Try this, the findOneAndUpdate operation does not wait for save operation to complete.
app.post('/api/account/transfer', (req, res, next) => {
const {
body
} = req;
const fields = ['sender', 'receiver', 'amount', 'balance'];
fields.forEach((field) => {
if (!body[field]) {
return res.send({
success: false,
message: 'Error: ' + field + ' cannot be blank!'
});
}
})
if (body.balance < body.amount || body.balance == 0) {
return res.send({
success: false,
message: 'Insufficient funds!'
});
}
//save the new transaction
let newTransaction = new Transaction();
// newTransaction = Object.assign(newTransaction, body); // If you want to copy all params from body to newTransaction
newTransaction.sender = body.sender;
newTransaction.receiver = body.receiver;
newTransaction.amount = body.amount;
newTransaction.save((err, transaction) => {
if (err) {
return res.send({
success: false,
message: 'Error: Server error.'
});
} else {
//update user balance
User.findOneAndUpdate({
/*query*/
}, {
/*body*/
}, (err, data) => {
if (err)
return res.send({
success: false,
message: 'Error: Server error.'
});
return res.send({
success: true,
message: 'Transfer Success!'
});
});
}
});
});

How to consume API which is created in nodejs-express-oracledb

I would want to consume GET/PUT/POST/DELETE API’s through a web page (HTML) which would be integrated on the Oracle JET.
The webpage will have one input free text option, where the user can type in to update the record.
i.e. If I click on one record on the JET dashboard, the API ‘GET /alluser/:FIRST_NAME – Read the profile of an user’ will be called,
it will display the detailed record with one text box as free text,
once the user enters text and hits submit, ‘PUT /process_post – Update the profile of an user’ API will be called, which will update the record.
Here is my script
var express = require('express');
var oracledb = require('oracledb');
var app = express();
var dbConfig = require('./dbconfig.js');
var bodyParser = require('body-parser');
var port = 3000;
app.use(bodyParser.json()); // Use body parser to parse JSON body
oracledb.outFormat = oracledb.OBJECT;
// Get a non-pooled connection
function run() {
oracledb.createPool({
user : dbConfig.user,
password : dbConfig.password,
connectString : dbConfig.connectString
},
function(err) {
if (err)
console.error("createPool() error: " + err.message);
else
var server = app.listen(port,
function () {
console.log('Server is listening on port ' + server.address().port);
});
});
}
function doGetConnection(res, cb) {
oracledb.getConnection(function (err, connection) {
if (err) {
res.set('Content-Type', 'application/json');
res.status(500).send(JSON.stringify({
status: 500,
message: "Error getting DB connection",
detailed_message: err.message
}));
} else {
cb(err, connection);
console.log(" Connection is connected");
}
});
}
app.post('/process_post', function (req, res) {
console.log("contenttype"+req.get('Content-Type'))
doGetConnection(res, function(err, connection) {
if (err)
return;
connection.execute(
"INSERT INTO TEST_TABLE(FIRST_NAME,LAST_NAME) VALUES (:FIRST_NAME,:LAST_NAME)",
[(req.body.FIRST_NAME),(req.body.LAST_NAME) ],
{ autoCommit: true,
outFormat:oracledb.OBJECT
},
console.log("check2"),
function (err) {
console.log("check3");
if (err) {
console.log("check4");
res.set('Content-Type', 'application/json');
res.status(400).send(JSON.stringify({
status: 400,
message: "Input Error",
detailed_message: err.message
}));
} else {
// Successfully created the resource
res.status(201).set('Location', '/process_post/' + req.body.FIRST_NAME).end();
}
doRelease(connection, "POST /process_post");
});
});
});
app.get('/alluser', function (req, res) {
doGetConnection(res, function(err, connection) {
if (err)
return;
connection.execute(
"SELECT * from employees",
function (err, result) {
if (err) {
res.set('Content-Type', 'application/json');
res.status(500).send(JSON.stringify({
status: 500,
message: "Error getting the farmer's profile",
detailed_message: err.message
}));
} else {
res.contentType('application/json').status(200);
res.send(JSON.stringify(result.rows));
}
doRelease(connection, "GET /bananas");
});
});
});
app.get('/alluser/:FIRST_NAME', function (req, res) {
doGetConnection(res, function(err, connection) {
if (err)
return;
connection.execute(
"SELECT * from employees WHERE first_name = :f",
{ f: req.params.FIRST_NAME },
function (err, result) {
if (err) {
res.set('Content-Type', 'application/json');
res.status(500).send(JSON.stringify({
status: 500,
message: "Error getting the farmer's profile",
detailed_message: err.message
}));
} else if (result.rows.length < 1) {
res.set('Content-Type', 'application/json');
res.status(404).send(JSON.stringify({
status: 404,
message: "FIRST_NAME doesn't exist",
detailed_message: ""
}));
} else {
res.contentType('application/json');
res.status(200).send(JSON.stringify(result.rows));
}
doRelease(connection, "GET /user/" + req.params.FIRST_NAME);
});
});
});
function doRelease(connection, message) {
connection.close(
function(err) {
if (err)
console.error(err);
else
console.log(message + " : Connection released");
});
}
run();
Thank you.
Oracle JET can help you make API calls.
Here's an example from their Cookbook: http://www.oracle.com/webfolder/technetwork/jet/jetCookbook.html?component=crud&demo=model
Have a look at the documentation for Collection and Model.
It's a lot to read if you're getting into it for the first time, so I'll give a quick example for a GET all:
var dataModel = oj.Model.extend({urlRoot: 'example.com'});
var modelInstance = new dataModel();
var CollectionConfig = {
model: modelInstance,
url: 'example.com'
};
var dataCollection = oj.Collection.extend(CollectionConfig);
var collectionInstance = new dataCollection();
collectionInstance.fetch({
success: function (collection, response, options) {
console.log(response);
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(errorThrown);
}
});

the variable i is not filled

I have declare the variable first. but if I do console.log(userinsertData) outside looping variable still not fill.
what i should do for solving this problem?
here my code:
var User = require('../models/user');
module.exports = {
myaction: function(req, res, next) {
var data = req.body,
userinsertData = [];
try {
data.forEach(function(item, index) {
var userdata = new User();
userdata.name = item.name;
userdata.age = item.age;
userdata.sex = item.sex;
userdata.save(function(err, data) {
if (err) {
res.send(err)
} else {
userinsertData.push(data);
}
});
})
} catch (e) {
res.json({
message: 'data not valid'
})
}
console.log(userinsertData);
res.json({
message: 'musician created!',
data: userinsertData
});
}
};
you should solve the problem as
async.eachSeries(data, function (info, callback) {
//here process your data and call callback() for next iteration
}, function (err) {
if (err) {
//this will be called after all iterations and in case of error
}else{
console.log('Well done :-!');
//this will be called after all interations successfully
}
});
this problem you are facing is because of asynchronous nature of nodejs and async helps you to introduce blocking.
Don't forget to include async
Use promise
var User = require('../models/user');
module.exports = {
myaction: function(req, res, next) {
var data = req.body,
userinsertData = [];
new Promise(function(resolve, reject) {
data.forEach(function(item, index) {
var userData = new User(item);
userData.save(function(err, data) {
// if error, reject
if(err) return reject(err);
// we have proceed all items in data, resolve it
else if(data.length - 1 === index) return resolve(userinsertData);
// not finished yet, keep proceeding
else userinsertData.push(data);
});
}).then(function(successResult) {
res.json({
message: 'musician created!',
data: successResult
});
}, function(errorResult) {
res.json({
message: 'data not valid'
});
});
}
};
Use callbacks
var User = require('../models/user');
module.exports = {
myaction: function(req, res, next) {
var data = req.body,
userinsertData = [];
function saveUser(callback) {
data.forEach(function(item, index) {
var userData = new User(item);
userData.save(function(err, data) {
// if error, return callback with error
if(err) return callback(err);
// we have proceed all items in data, return data
else if(data.length - 1 === index) callback(null, userinsertData);
// not finished yet, keep proceeding
else userinsertData.push(data);
});
}
saveUser(function(err, users) {
if(err) return res.json({message: 'data not valid'});
res.json({
message: 'musician created!',
data: users
});
});
}
};
This is what async package does internally

Value not being updated in DB, node.js and mongoose

I am trying to update the value of my model and it does not work.
The weird thing is that I am printing out the result and it looks different than what I see in my database by using Robomongo.
Any thoughts why this happens?
Here is my code:
exports.create = function(req, res) {
var productId = req.query.product;
if (productId) {
Request.createWizard(req.user, { productId: productId }, function(err, request) {
Product.findById(productId, function(err, product) {
if (err) {
return console.log('oh no! error', err);
} else {
if (product.price =! 0 )
request.status = 'ready';
console.log(request);
(Here I see in the terminal: status = ready)
}
});
req.flash('success', { msg: 'Your request has been successfully created.' });
res.redirect('/discover');
});
} else {
var pages = require('../../schemas/wizard/request')();
res.render('requests/form', {
title: 'Make a Request',
pages: pages,
saveState: false
});
}
};
When I am checking the database status is still on pending.
You're changing the status property, but you're not saving the document back to the database after doing so:
Request.createWizard(req.user, { productId: productId }, function(err, request) {
Product.findById(productId, function(err, product) {
if (err) {
return console.log('oh no! error', err);
} else {
if (product.price !== 0) {
request.status = 'ready';
request.save(function(err) { // <-- save it back to the database
if (err) {
console.log('oh no! error', err);
} else {
console.log(request);
}
});
}
}
});
req.flash('success', { msg: 'Your request has been successfully created.' });
res.redirect('/discover');
});

Resources