Ad

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 ?

Ad

Answer

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");
        }
      }
    }
  );
});
Ad
source: stackoverflow.com
Ad