为了账号安全,请及时绑定邮箱和手机立即绑定

在 await model.save in nodejs/express

在 await model.save in nodejs/express

ibeautiful 2022-08-18 10:09:04
我有2个模型员工和任务列表。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 configvar 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);我有一个编辑路由,其中我为任务分配了多个受托人。  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(',');我能够将员工推送到 tasklist.taskAssignee,还可以执行 tasklist.save()。没有错误。但是,更新不会保留在 mongoDB 中。
查看完整描述

1 回答

?
慕尼黑5688855

TA贡献1848条经验 获得超2个赞

我看urcode,似乎你没有等待承诺来解决


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..

整个示例。


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");

        }

      }

    }

  );

});


查看完整回答
反对 回复 2022-08-18
  • 1 回答
  • 0 关注
  • 69 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信