简体   繁体   English

使用猫鼬无法向数据库添加多个对象

[英]cant add more than one object into db using mongoose

I have a function that is supposed to add new item each time there is a match as below: 我有一个应该在每次匹配时添加新项的函数,如下所示:

    function getTimeEntriesFromWorksnap(error, response, body) {
    //console.log(response.statusCode);
    var counter = 1;
    if (!error && response.statusCode == 200) {
        parser.parseString(body, function (err, results) {
            var json_string = JSON.stringify(results.time_entries);
            var timeEntries = JSON.parse(json_string);

            _.forEach(timeEntries, function (timeEntry) {
                _.forEach(timeEntry, function (item) {
                    Student.findOne({'worksnap.user.user_id': item.user_id[0]})
                        .populate('user')
                        .exec(function (err, student) {
                            if (err) {
                                throw err;
                            }

                            var newTimeEntry = _pushToObject(student.worksnap.timeEntries, item);

                            student.worksnap.timeEntries = {};
                            student.worksnap.timeEntries = newTimeEntry;

                            student.save(function (err) {
                                if (err) {
                                    //return res.status(400).send({
                                    //    message: errorHandler.getErrorMessage(err)
                                    //});
                                } else {
                                    //res.json(item);
                                }
                            });

                        });
                });
            });
        });
    }
}

For some reason it is only inserting once for each student that it finds. 由于某种原因,它只会为找到的每个学生插入一次。 And my Student schema looks like this: 我的学生模式如下所示:

    var StudentSchema = new Schema({
    firstName: {
        type: String,
        trim: true,
        default: ''
        //validate: [validateLocalStrategyProperty, 'Please fill in your first name']
    },
    lastName: {
        type: String,
        trim: true,
        default: ''
        //validate: [validateLocalStrategyProperty, 'Please fill in your last name']
    },
    worksnap: {
        user: {
            type: Object
        },
        timeEntries: {
            type: Object
        },
     }
   });

Any solution? 有什么办法吗?

My Guess is its always pushing the last one... closures ... 我的猜测是,它一直在推动最后一个... closures ...

function getTimeEntriesFromWorksnap(error, response, body) {
    //console.log(response.statusCode);
    var counter = 1;
    if (!error && response.statusCode == 200) {
        parser.parseString(body, function (err, results) {
            var json_string = JSON.stringify(results.time_entries);
            var timeEntries = JSON.parse(json_string);

            _.forEach(timeEntries, function (timeEntry) {
                _.forEach(timeEntry, function (item) {
                    saveStudent(item);
               });
            });
        });
    }
}

Below is saveStudent function 下面是saveStudent函数

function saveStudent(item) {

    Student.findOne({
            'worksnap.user.user_id': item.user_id[0]
        })
        .populate('user')
        .exec(function(err, student) {
            if (err) {
                throw err;
            }

            var newTimeEntry = _pushToObject(student.worksnap.timeEntries, item);

            student.worksnap.timeEntries = {};
            student.worksnap.timeEntries = newTimeEntry;

            student.save(function(err) {
                if (err) {
                    //return res.status(400).send({
                    //    message: errorHandler.getErrorMessage(err)
                    //});
                } else {
                    //res.json(item);
                }
            });

        });
}

OR 要么

wrap it inside a closure... 包裹在一个封闭的...

function getTimeEntriesFromWorksnap(error, response, body) {
    //console.log(response.statusCode);
    var counter = 1;
    if (!error && response.statusCode == 200) {
        parser.parseString(body, function(err, results) {
            var json_string = JSON.stringify(results.time_entries);
            var timeEntries = JSON.parse(json_string);

            _.forEach(timeEntries, function(timeEntry) {
                _.forEach(timeEntry, function(item) {
                  (function(item){
                    Student.findOne({
                            'worksnap.user.user_id': item.user_id[0]
                        })
                        .populate('user')
                        .exec(function(err, student) {
                            if (err) {
                                throw err;
                            }

                            var newTimeEntry = _pushToObject(student.worksnap.timeEntries, item);

                            student.worksnap.timeEntries = {};
                            student.worksnap.timeEntries = newTimeEntry;

                            student.save(function(err) {
                                if (err) {
                                    //return res.status(400).send({
                                    //    message: errorHandler.getErrorMessage(err)
                                    //});
                                } else {
                                    //res.json(item);
                                }
                            });

                        });
                  }(item))
                });
            });
        });
    }
}

Can you use async library and check out... 您可以使用async库并签出...

var async = require('async');
async.map(timeEntries, function (timeEntry, next) {
   async.map(timeEntry, function (item, next) {
      //your code.
  });
});

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM