Sending data before saving Node Js - javascript

I have this function with a Post that I want to insert the data in the database (MongoDB). First of all, I want to save the data in the model "Recetas" and after in the model "Users". And finally send the response. My problem is that is not saving in the model Users and is sending the data before saving.
This is my code
addReceta = function (req, res) {
User.findById(req.params.id, function(err, user){
if (!user){
res.send(404, 'User not found');
}
else{
fs.readFile(req.files.file.path, function (err, data) {
var id = crypto.randomBytes(16).toString("hex");
var newPath = pwd + id +req.files.file.originalFilename;
fs.writeFile(newPath, data, function (err) {
var date_created = new Date();
var date = date_created.toISOString().slice(0,10);
var receta = new Receta({
Titulo: datos2.titulo,
Username: datos2.username,
Ingredientes: datos2.ingredientes,
Dificultad: datos2.dificultad,
Descripción: datos2.descripcion,
Personas: datos2.personas,
Date_Created: date_created,
Tiempo: datos2.tiempo,
user_id: req.params.id,
imageUrl: URL + id + req.files.file.originalFilename
})
receta.save(function(err) {
if(!err) {
console.log('Created in Receta');
}
else {
console.log(error);
}
});
var UserReceta = ({
_id: receta._id,
Titulo : receta.Titulo,
Username : receta.Username,
Descripción : receta.Descripción,
Ingredientes : receta.Ingredientes,
Dificultad : receta.Dificultad,
Personas : receta.Personas,
Date_Created: date_created,
Tiempo : receta.Tiempo,
user_id : receta.user_id,
imageUrl: receta.imageUrl
});
user.Recetas.push(UserReceta);
user.save(function (err){
if (!err) {
console.log('Created in User Recetas');
}
else {
res.send(500, err);
}
});
res.send(receta);
});
});
};
});
};

Put your res.send(receta); inside the callback after saving in Users, right after the console.log:
console.log('Created in User Recetas');
res.send(receta);

Related

unable to find records in mongobd after await model.save in nodejs/express.js application

I have 2 models employee and tasklist.
var mongoose=require("mongoose");
var findOrCreate = require('mongoose-findorcreate');
var uniqueValidator = require('mongoose-unique-validator');
var employeeSchema = new mongoose.Schema({
empId : { type : Number , unique : true, required : true },
empName : { type : String , unique : true, required : true },
empTeam : { type : String , required : true },
created : {type : Date, default : Date.now}
});
employeeSchema.plugin(findOrCreate,uniqueValidator);
module.exports = mongoose.model("Employee", employeeSchema);
// Mongoose Tasklist Model config
var mongoose=require("mongoose");
var findOrCreate = require('mongoose-findorcreate');
var uniqueValidator = require('mongoose-unique-validator');
var tasklistSchema = new mongoose.Schema({
taskId : { type : Number , unique : true, required : true },
taskDesc : { type : String , unique : true, required : true },
taskDetails : {type : String},
taskAssignee : [{
type:mongoose.Schema.Types.ObjectId,
ref:"Employee"
}],
startDate: Date,
dueDate: Date,
taskStatus: String,
created : {type : Date, default : Date.now},
});
tasklistSchema.plugin(findOrCreate, uniqueValidator);
module.exports = mongoose.model("Tasklist", tasklistSchema);
I have an edit route where I am assigning multiple assignees to the task.
router.post("/tasklist/:id/edit", function(req,res){
Tasklist.findOneAndUpdate({_id:req.params.id},req.body.tasklist, async function(err, tasklist){
if(err){
req.flash("error", "Unable to update the tasklist record : "+err.message);
res.redirect("/employee");
} else {
var emp_id=req.body.taskAssignee.split(',');
try {
emp_id.forEach(assignee => {
return new Promise (function(resolve, reject){
Employee.findById(assignee, function(err, employee){
if(err){
console.log("error in finding employee :"+assignee);
reject("There was an error loading the employee data in to the database : "+err.message);
} else {
tasklist.taskAssignee.push(employee);
console.log("employee saved");
resolve("Employee records uploaded successfully");
}
});
});
});
console.log("Tasklist Saving....")
let savetasklist= await tasklist.save();
console.log("Tasklist Saved : ");
req.flash("success", "Updated Tasklist"+req.body.tasklist);
res.redirect("/tasklist");
} catch (err){
req.flash("error", "Updating Tasklist"+err);
res.redirect("/tasklist");
}
}
});
});
I am able to push the employee to tasklist.taskAssignee and also do a tasklist.save(). There are no errors. However, the update is not persisted in the mongoDB.
The console output looks like this.
some more logging info.
connection successful
Tasklist Saving....
employee saved: Assignee:5ebebe1476911d570448ee44Employee:{
_id: 5ebebe1476911d570448ee44,
empId: 32141,
empName: 'adsdasd',
empTeam: 'C Team',
created: 2020-05-15T16:06:44.342Z,
__v: 0
}
record pushed
Tasklist Saved :
{
taskAssignee: [
{
_id: 5ebebe1476911d570448ee44,
empId: 32141,
empName: 'adsdasd',
empTeam: 'C Team',
created: 2020-05-15T16:06:44.342Z,
__v: 0
}
],
_id: 5ebf1c4830f79c178c7f9905,
taskId: 17562,
taskDesc: 'WTX subscription process',
dueDate: 2020-05-25T18:30:00.000Z,
created: 2020-05-15T22:48:40.091Z,
__v: 0
}
Need help on this. Why is tasklist not getting persisted with employee ?
I look urcode, seems u are not waiting for promise to resolve
const promises = emp_id.map((assignee) => {
return new Promise(function (resolve, reject) {
Employee.findById(assignee, function (err, employee) {
if (err) {
console.log("error in finding employee :" + assignee);
reject(
"There was an error loading the employee data in to the database : " +
err.message
);
} else {
tasklist.taskAssignee.push(employee);
console.log("employee saved");
resolve("Employee records uploaded successfully");
}
});
});
});
await Promise.all(promises) // here wait..
Whole example.
router.post("/tasklist/:id/edit", function (req, res) {
Tasklist.findOneAndUpdate(
{ _id: req.params.id },
req.body.tasklist,
async function (err, tasklist) {
if (err) {
req.flash(
"error",
"Unable to update the tasklist record : " + err.message
);
res.redirect("/employee");
} else {
var emp_id = req.body.taskAssignee.split(",");
try {
const promises = emp_id.map((assignee) => {
return new Promise(function (resolve, reject) {
Employee.findById(assignee, function (err, employee) {
if (err) {
console.log("error in finding employee :" + assignee);
reject(
"There was an error loading the employee data in to the database : " +
err.message
);
} else {
tasklist.taskAssignee.push(employee);
console.log("employee saved");
resolve("Employee records uploaded successfully");
}
});
});
});
await Promise.all(promises)
console.log("Tasklist Saving....");
let savetasklist = await tasklist.save();
console.log("Tasklist Saved : ");
req.flash("success", "Updated Tasklist" + req.body.tasklist);
res.redirect("/tasklist");
} catch (err) {
req.flash("error", "Updating Tasklist" + err);
res.redirect("/tasklist");
}
}
}
);
});

stored procedure in node.js

im receiving an error when running this code
Error: ER_BAD_FIELD_ERROR: Unknown column 'employee_id' in 'field list'
the output is this
{ employee_id: '6',
employee_name: 'test',
employee_contact: 'test' }
this is my stored procedure code
CREATE DEFINER=`root`#`localhost` PROCEDURE `test3`(
in empid int(11) ,
in name1 varchar(45) ,
in contact varchar(45)
)
BEGIN
insert into test_table (employee_id , employee_name , employee_contact)
values (empid,name1,contact);
END
this is my index.js
router.post('/test', function (req, res, next) {
try {
var reqObj = req.body;
console.log(reqObj);
req.getConnection(function (err, conn) {
if (err) {
console.error('SQL Connection error: ', err);
return next(err);
} else {
// let employee_id = reqObj.employee_id
// let employee_name =reqObj.name1
// let employee_contact = reqObj.contact
var insertSql6 = "CAll test3(employee_id, employee_name, employee_contact)";
var insertValues6 = {
"employee_id": reqObj.empid,
"employee_name": reqObj.name1,
"employee_contact": reqObj.contact
};
var query = conn.query(insertSql6,insertValues6, function (err, result) {
if (err) {
console.error('SQL error: ', err);
return next(err);
}
console.log(result);
var test_Id = result.insertId;
res.json({
"test_id": test_Id
});
});
}
});
} catch (ex) {
console.error("Internal error:" + ex);
return next(ex);
}
});

Error: Cannot enqueue Query after invoking quit

when running the code below im having an Error: Cannot enqueue Query after invoking quit. i need to insert some data into two table .
can you help me to correct the code im really new here in node.js thank you so much.
Create Contact Service.
router.post('/contactinformationdetails', function (req, res, next) {
try {
var reqObj = req.body;
console.log(reqObj);
req.getConnection(function (err, conn) {
if (err) {
console.error('SQL Connection error: ', err);
return next(err);
} else {
var insertSql1 = "INSERT INTO contact_person SET ? ";
var insertValues1 = {
"site_name": reqObj.sitNam,
"first_name": reqObj.firName,
"last_name": reqObj.lastName,
"position": reqObj.posId,
"contact_number": reqObj.conNum,
"organization": reqObj.orga1,
"email_add": reqObj.emaAdd1,
};
var query = conn.query(insertSql1, insertValues1, function (err, result) {
if (err) {
console.error('SQL error: ', err);
return next(err);
}
console.log(result);
var Contact_Id = result.insertId;
res.json({
"Cont_id": Contact_Id
});
var insertSql5 = "INSERT INTO address_contactperson SET ? ";
var insertValues5 = {
"address_name": reqObj.addNam,
"address_one": reqObj.addOne,
"address_two": reqObj.addTwo,
"city": reqObj.city,
"province": reqObj.prov
};
var query1 = conn.query(insertSql5, insertValues5, function (err, result) {
if (err) {
console.error('SQL error: ', err);
return next(err);
}
console.log(result);
});
});
}
});
} catch (ex) {
console.error("Internal error:" + ex);
return next(ex);
}
});
You must try this with mongodb(MongoDB is an open-source document database and leading NoSQL database) the most easy and efficient way.
router.all('/todo/create', function (req, res) {
var taskcreate = req.Collection;
var task = req.body.task;
var date = req.body.date;
var status1 = req.body.status1;
var userid = req.body.userid;
var users = req.Collection;
var record = new taskcreate({
task: task,
date: date,
status1: status1,
userid: userid
});
if (task.length > 0) {
record.save(function (err, result) {
if (err) {
res.json({status: 0, message: err})
} else {
res.json({status: 1, userid: userid, task: task, date: date, message: " success"});
}
})
} else {
res.json({status: 0, msg: "Invalid Fields"});
}
});

embedded insertion of Array in mongodb

I have to try to store array data inside MongoDB using this query below. but every time I run this query its show success message without data means an empty array inside MongoDB,
my requirement is to store array data inside MongoDB as below query.
1). This is my node js script
this.childQuestionInfo = function(req, res, next){
try{
var quizArr = [];
var quizObj = {
'child.quiz.questionId' : req.params.questionId,
'child.quiz.score' : req.params.score,
'child.quiz.time' : new Date().toISOString()
};
quizArr.push(quizObj);
var userObj = {
'userid' : req.params.userId,
'quiz' : quizArr
};
var childinfoSave = new QuizChildInfo(userObj);
childinfoSave.save(function(err, data){
if(err) return next(err);
res.send("Child questionId score and date saved successfully" + data);
console.log("Child questionId score and date saved successfully");
});
}catch(err){
console.log('Error While Saving the child questionId score and Date ' +err);
return next(err);
}
};
2). This is my child schema
userId:{
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
},
quiz:[
{
questionId:{
type: mongoose.Schema.Types.ObjectId,
ref: 'question'
},
score:{type:Number},
time:{type:String}
}
]
3). This is my output screen via postman
"Child questionId score and date saved successfully
{ __v: 0,\n _id: 57b9ac672c5791f8097d2132,\n levelsAttempted: [],\n quiz: [ { _id: 57b9ac672c5791f8097d2133 } ] }"
Try this using $push
this.childQuestionInfo = function(req, res, next){
try{
var queryObj={};
var childObj={};
var queryObj = {userid: req.params.userId};
var options = {safe: true, upsert: true};
childObj.questionId' : req.params.questionId,
childObj.score' : req.params.score,
childObj.time' : new Date().toISOString()
};
QuizChildInfo.findOneAndUpdate( queryObj, { $push: childObj }, options, function (err, data) {
if(err) return next(err);
res.send("Child questionId score and date saved successfully" + data);
console.log("Child questionId score and date saved successfully");
});
}catch(err){
console.log('Error While Saving the child questionId score and Date ' +err);
return next(err);
}
};

Cannot read property "rid" of undefined

[TypeError: Cannot read property 'rid' of undefined]
Is the error that I get when I try to execute this controller on my post route.
I've tested it out with Postman.
I've tried to console.log(result) but I get undefined.
My query gets executed and my row is inserted into my table. I've checked it. Password is also hashed.
The problem is that I don't get any out binds that should be returned.
Problematic code (IMO) is
...
.then(function(result) {
console.log(result);
cb(null, {
id: result.outBinds.rid[0],
email: result.outBinds.remail[0],
role: result.outBinds.rrole[0]
});
})
...
oracle-NodeDB Wrapper
var oracledb = require('oracledb');
module.exports.OBJECT = oracledb.OBJECT;
function executeSQL(config ,sql, bindParams , options) {
return new Promise(function(resolve, reject) {
oracledb.getConnection(
config,
function(err, connection) {
if (err) {
return reject(err);
}
connection.execute(
sql,
bindParams,
options,
function(err, result) {
if (err) {
doRelease(connection);
return reject(err);
}
resolve(result);
doRelease(connection);
});
});
});
}
function doRelease(connection) {
connection.release(
function(err) {
if (err) {
console.log(err.message);
}
}
);
}
module.exports.executeSQL = executeSQL;
Controller
var database = require('../database/oracledbWrapper');
var dbconfig = require('../database/dbconfig').dbconfig;
var jwt = require('jsonwebtoken');
var bcrypt = require('bcrypt');
exports.createUser = function(req, res, next) {
var user = {
email: req.body.email
};
var unhashedPassword = req.body.password;
bcrypt.genSalt(10, function(err, salt) {
if (err) {
return next(err);
}
bcrypt.hash(unhashedPassword, salt, function(err, hash) {
if (err) {
return next(err);
}
user.hashedPassword = hash;
insertUser(user, function(err, user) {
var payload;
if (err) {
return next(err);
}
payload = {
sub: user.email,
role: user.role
};
res.status(200).json({
user: user,
token: jwt.sign(payload, config.jwtSecretKey, {expiresInMinutes: 60})
});
});
});
});
}
function insertUser(user, cb) {
var bindParams = {
email: user.email.toLowerCase(),
password: user.hashedPassword,
rid: {
type: database.NUMBER,
dir: database.BIND_OUT
},
remail: {
type: database.STRING,
dir: database.BIND_OUT
},
rrole: {
type: database.STRING,
dir: database.BIND_OUT
}
};
database.executeSQL(
dbconfig,
'insert into express_users (email, password, role ) values ( :email, :password, \'BASE\' ) returning id, email, role into :rid , :remail, :rrole',
bindParams,
{}
)
.then(function(result) {
console.log(result);
cb(null, {
id: result.outBinds.rid[0],
email: result.outBinds.remail[0],
role: result.outBinds.rrole[0]
});
})
.catch(function(err) {
console.log(err);
next(err);
});
}
Route
var RESTfulAPICon = require('../controllers/RESTfulAPI');
var indexCon = require('../controllers/index');
var views = require('express').Router();
views.route('/users').post(RESTfulAPICon.createUser);
exports.views = views;
The problem was in my wrapper , mainly here
module.exports.OBJECT = oracledb.OBJECT;
I export only the OBJECT property , but I try to access BIND_OUT properties later on. And they are non existent.
If I do the full export like this
module.exports.OBJECT = oracledb;
Then I can access BIND_OUT properties.

Categories