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);
}
};
Related
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");
}
}
}
);
});
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);
I have problem to insert a value inside an array using node.js and mongodb
1). MongoDb Schema
var userScore = new Schema({
child: {
quiz_level: {
current_level: {type:Number},
level_attempted: {
type: Array,
level_id: {type:Number},
level_complete: {type:Boolean},
level_score: {type:Number}
}
}
}
});
2). Node js
try{
// var quiz = levelScoreQuiz.child;
var userObj = {
"child.quiz_level.level_attempted.level_score": req.body.score
};
var user = new levelScoreQuiz(userObj);
user.save(function(err, result){
if (err) {
console.log('Error While Saving the reuslt ' +err)
} else {
console.log("User score saved successfully");
res.json(result);
}
});
} catch(err){
console.log('Error While Saving the reuslt ' +err);
return next(err);
}
3). Json result
This will shows the empty result of array insertions
{
"__v": 0,
"_id": "57832f610118546713d23466",
"child": {
"quiz_level": {
"level_attempted": [] //This is the empty array
}
}
}
How can I add object to my nested Array in PartnerSchema?
I separate documents, because in the future there will be more of nested arrays.
This is my schema:
var productSchema = new mongoose.Schema({
name: String
});
var partnerSchema = new mongoose.Schema({
name: String,
products: [
{
type: mongoose.Schema.Types.ObjectId,
ref: 'Product'
}]
});
module.exports = {
Partner: mongoose.model('Partner', partnerSchema),
Product: mongoose.model('Product', productSchema)
}
And this is my backend:
var campSchema = require('../model/camp-schema');
router.post('/addPartner', function (req, res) {
new campSchema.Partner({ name : req.body.name }).save(function (err, response) {
if (err) console.log(err);
res.json(response);
});
});
router.post('/addProduct', function (req, res) {
campSchema.Partner.findByIdAndUpdate({ _id: req.body.partnerId },
{
$push: {
"products": {
name: req.body.dataProduct.name
}
}
}, { safe: true }, function (err, response) {
if (err) throw err;
res.json(response);
});
});
I can add Partner by using /addPartner and it works fine.
Problem is with second function /addProduct I can't add Product to Array in Partner Schema. I have an error: CastError: Cast to undefinded failed for value "[object Object]" at path "products"
Since the products field in Partner model is an array that holds _id refs to the Product model, you are supposed to push an _id to the array, not an object hence Mongoose complains with an error.
You should restructure your code to allow the saving of the Product _id ref to the Partner model:
router.post('/addProduct', function (req, res) {
var product = new campSchema.Product(req.body.dataProduct);
product.save(function (err) {
if (err) return throw err;
campSchema.Partner.findByIdAndUpdate(
req.body.partnerId,
{ "$push": { "products": product._id } },
{ "new": true },
function (err, partner) {
if (err) throw err;
res.json(partner);
}
);
});
});
I am trying to print out to the console the name of a Team in my database, here is the code:
var Team = require('../schemas/Team').Model;
app.get('/match', function(req, res) {
var key = 1359407087999; // Team Key
Team.findByKey(key, function(err, team) {
util.log(team);
if (err) {
util.log("Error occured");
}
if (!team) {
util.log("The team does not exist");
} else {
res.send("Found team: " + team.name);
}
});
});
The code gets the Team successfully where util.log(team) is. It prints this to the console:
{
__v: 0,
_id: 5106e7ef9afe3a430e000007,
name: 'Team Name',
key: 1359407087999
}
This also works when sending it to the web page as well.
But when I try to send the Team's name to the web page, I get the following output with the res.send method => Found team: undefined...And when I try to output team.name instead of team to the console, I get the error Cannot call method 'toString' of undefined
Here is my Team mongoose schema as well:
var Team = new Schema({
'key' : {
unique : true,
type : Number,
default: getId
},
'name' : { type : String,
validate : [validatePresenceOf, 'Team name is required'],
index : { unique : true }
}
});
Team.statics.findByKey = function(key, cb){
return this.find({'key' : key}, cb);
};
module.exports.Schema = Team;
module.exports.Model = mongoose.model('Team', Team);
show team
app.get('/show/team/:key', function(req, res){
util.log('Serving request for url[GET] ' + req.route.path);
Team.findByKey(req.params.key, function(err, teamData){
util.log(teamData[0]);
if (!err && teamData) {
teamData = teamData[0];
res.json({
'retStatus' : 'success',
'teamData' : teamData
});
} else {
util.log('Error in fetching Team by key : ' + req.params.key);
res.json({
'retStatus' : 'failure',
'msg' : 'Error in fetching Team by key ' + req.params.key
});
}
});
});
Name is unique, so you should use findOne instead of find.
Team.statics.findByKey = function(key, cb){
return this.findOne({'key' : key}, cb);
};