简体   繁体   English

Nodejs和mongoose,迭代数据库以创建一个新的

[英]Nodejs and mongoose, iterate database to create a new one

I have a collection with unordered student exams with this mongoose model: 我有一个猫鼬模型的学生考试无序集合:

var ExamSchema = new Schema({
  firstName: String,
  lastName: String,
  studentCode: String,
  examType: String,
  examDate: String,
  examResult: String
});

I need to create a new collection grouping exams based on student's code as in this model: 我需要根据此模型中的学生代码创建一个新的集合分组考试:

var StudentSchema = new Schema({
  firstName: String,
  lastName: String,
  studentCode: String,
  test: [{
    type: String,
    date: String,
    result: String
  }]
});

I tried this function but it just inserts all the students and never finds the student code. 我尝试了此功能,但它只插入所有学生,却找不到学生代码。

function rebuildDb(err, done) {
 Exam.find({} , function(err, doc) {
  if(err) return err;
  doc.map( function(exam) {
        Student.findOne({ studentCode: exam.studentCode }, function(err, foundExam) {
         if(err) return callback(err);
         if(foundExam == null) {
           var student = new Student ({
             firstName: exam.firstName,
             lastName: exam.lastName,
             studentCode: exam.studentCode,
             test: [{
                type: exam.examType,
                date: exam.examDate,
                result: exam.examResult
              }],
           });
             student.save(function(err, newStudent) {
             if(err) return err;
             console.log("New student created: " + student.studentCode);
           });
         } else {
           Student.update({ studentCode: exam.studentCode }, { "$push": {
              test: {
                type: exam.examType,
                date: exam.examDate,
                result: exam.examResult
              }
            } }, function(err, newTest) {
           if(err) return err;
           console.log("New test for student: " + student.studentCode);
           });
         }
     });
  });
});
};

I think it is a sync/async issue, but I don't know how to handle it. 我认为这是一个同步/异步问题,但我不知道如何处理。 What's the best practice in a case like this? 在这种情况下,最佳做法是什么?

Thanks in advance. 提前致谢。

Try this 尝试这个

const saveStudent = (exam) => {
    return new Promise((resolve, reject) => {
        const student = new Student({
            firstName: exam.firstName,
            lastName: exam.lastName,
            code: exam.code,
            test: [{
                type: exam.examType,
                date: exam.examDate,
                result: exam.examResult
            }],
        });
        student.save(function (err, newStudent) {
            if (err) return reject(err);
            console.log("New student created: " + student.code);
            resolve(newStudent);
        });
    });
}

const updateStudent = (exam) => {
    return new Promise((resolve, reject) => {
        Student.update({
            code: exam.code
        }, {
            "$push": {
                test: {
                    type: exam.examType,
                    date: exam.examDate,
                    result: exam.examResult
                }
            }
        }, function (err, newTest) {
            if (err) return reject(err);
            console.log("New test for student: " + student.code);
            resolve(newTest);
        });
    });
}

const findExam = async () => {
    const doc = await Exam.find({}).exec();
    doc.forEach(exam => {
        const foundExam = await Student.findOne({
            code: exam.code
        }).exec();
        if (foundExam == null) {
            await saveStudent(exam);
        } else {
            await updateStudent(exam);
        }
    });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 NodeJS,Mongoose,Express:检查数据库是否为新用户 - NodeJS, Mongoose, Express: Check Database if User is New 在猫鼬的nodejs中创建一个模式,仅用于一条记录 - Create a schema in mongoose nodejs for one record only 是否可以使用 ZCCADCDEDB567ABAE643E15DCF0974E503Z 在 MongoDB 中创建新数据库? - Is it possible to create a new database in MongoDB with Mongoose? 调用模式方法而无需使用Nodejs / Mongoose创建新的Model对象 - Call schema method without create a new Model object with Nodejs/Mongoose 有没有办法删除数据库中的所有 collections 除外? nodejs mongodb,mongoose - Is there a way to delete all collections in a database except the one ? nodejs mongodb, mongoose 如何在每次新订阅应用程序时在 mongoose 中创建新数据库 - How to create a new database in mongoose on each new subscription to an application nodejs仅能在数据库中创建一个用户 - nodejs only able to create one user in the database MongoDB和Mongoose访问一个数据库,同时对另一个数据库进行身份验证(NodeJS,Mongoose) - MongoDB & Mongoose accessing one database while authenticating against another (NodeJS, Mongoose) 使用mongoose api和nodejs搜索数据库? - searching database with mongoose api and nodejs? Mongoose更新* ONE *字段如果找到,否则创建新的所有字段 - Mongoose Update *ONE* Field if Found Otherwise Create New With All Fields
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM