猫鼬不在循环中保存所有文档 [英] Mongoose not saving all documents in loop
本文介绍了猫鼬不在循环中保存所有文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
所以在Express应用程序中,我有以下用于POST api的代码:
So I have the following code in an Express app for the POST api:
var dashSchema = new mongoose.Schema({
key: 'string',
status: 'string',
assignee: 'string',
summary: 'string'
});
var dashData = mongoose.model('dashData', dashSchema);
app.post('/api/data', function(req, res) {
var issues = req.body.issues;
for (var i=0;i<issues.length;i++) {
dashData.create({key: issues[i].key, status: issues[i].fields.status.name, assignee: issues[i].fields.assignee, summary: issues[i].fields.summary});
}
res.end();
});
每当我发布5个问题"的数组时,只有前两个会被写入MongoDB.我以为这是因为它可以遍历整个循环所花费的时间,但是我不知道如何使它写入所有数据,然后返回响应.
Whenever I post an array of 5 "issues" only the first two are being written to the MongoDB. I assume this is because that is all it can write in the time it takes to iterate through the loop, but I don't know how to make it write all of the data, and then return the response.
有什么想法吗?
推荐答案
在猫鼬中, .create
返回一个承诺.安装诸如 bluebird
之类的Promise库,以使您可以访问 Promise.all
,您可以执行以下操作:
In Mongoose, .create
returns a promise. Install a promise library like bluebird
to give you access to Promise.all
and you can do this:
var Promise = require('bluebird'); // could also be Q or another A+ library
app.post('/api/data', function(req, res, next) {
var issues = req.body.issues;
// map the issues to an array of promises for created dashData docs
var createdPromises = issues.map(function(issue){
return dashData.create({key: issue.key, status: issue.fields.status.name, assignee: issue.fields.assignee, summary: issue.fields.summary}); // returns a promise
});
Promise.all(createdPromises).then(function(results){
res.json(results); // only sends when all docs have been created
}).then(null, next); // error handler - pass to `next`
});
这篇关于猫鼬不在循环中保存所有文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文