将对象推入mongodb中的另一个对象时出错 [英] Error pushing objects into another object in mongodb

查看:89
本文介绍了将对象推入mongodb中的另一个对象时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

req.body.courses具有要添加到特定类别的课程的ID的倍数,问题是,当我的代码运行时,它可以节省一门课程的时间,有时是四到五次,具体取决于数量of循环.

req.body.courses has multiples id's of courses that I want to add to a specific categorie, the problem is that when my code runs it save a course more that one time, sometimes four or five times, depending on the number of loops it does.

功能:

router.post('/categories/:cat_id/', function (req, res) {
    Categorie.findById(req.params.cat_id, function(err, categorie){
    if(err){
      console.log(err);
    } else {
      var courses = req.body.courses;
      courses.forEach(function (course){
          Course.findOne({  _id:  course }, function(err, foundCourse) {
              if(err){
                  console.log(err);
              } else {
                  categorie.courses.push(foundCourse._id);
                  categorie.save();
              }
          });
      });
    }
  });
  return res.redirect('/dash');
});

CategorieSchema:

The CategorieSchema:

var categorieSchema = mongoose.Schema({
   name: String,
   courses: [
        {
            type: mongoose.Schema.Types.ObjectId,
            ref: "Course"
        }    
    ]
});

以下是尝试向类别添加4门课程的示例:

Here is an example of trying to add 4 courses to the categorie:

{ "_id" : ObjectId("5a871964a6b4820ecf7abaa7"), "courses" : [ ObjectId("5a870a7374486e0b0d69f710"), ObjectId("5a870a7a74486e0b0d69f711"), ObjectId("5a870a6974486e0b0d69f70f"),   
 ObjectId("5a870a7374486e0b0d69f710"), ObjectId("5a870a7a74486e0b0d69f711"), ObjectId("5a870a6974486e0b0d69f70f"), 
 ObjectId("5a870a7374486e0b0d69f710"), ObjectId("5a870a7a74486e0b0d69f711"), ObjectId("5a870a6974486e0b0d69f70f") ], "name" : "test2", "__v" : 3 }

推荐答案

Node.js是异步的,它不会等待循环完全执行,并且每次在现有数组中添加_id都会因为这样做会增加2-3时间.

Node.js Is async, It does not wait for the loop to execute completely and each time you are adding _id in existing array because of that adds 2-3 times.

一旦我没有测试过,就试试看.

Try this once I have not tested this.

const findOne = (course) => {
    return new Promise((resolve, reject) => {
        Course.findOne({
            _id: course
        }, (err, foundCourse) => {
            if (err)
                return reject(err);
            return resolve(foundCourse._id);
        });
    });
}

router.post('/categories/:cat_id/', function (req, res) {
    Categorie.findById(req.params.cat_id, function (err, categorie) {
        if (err) {
            console.log(err);
            res.status(400).json(err);
        } else {
            var courses = req.body.courses;

            Promise.all(courses.map((course) => {
                return findOne(course);
            })).then((data) => {
                // check if course id already there skip
                data = data.filter((course) => {
                    return !categorie.courses.includes(course);
                });
                categorie.courses = categorie.courses.concat(data);
                categorie.save();
                return res.redirect('/dash');
            }).catch((err) => {
                console.log(err);
                res.status(400).json(err);
            });
        }
    });
});

这篇关于将对象推入mongodb中的另一个对象时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆