在post请求中使用mongodb插入多个文档
Inserting multiple documents with mongodb in a post request
在同一个请求中使用mongodb插入多个文档我得到了未定义的值。
.post(function (req, res) {
...
Item.create(data)
.then(function (item) {
var modelOtherItem;
OtherItem.create({
...
}).then(function (otherItem){
modelOtherItem = otherItem;
modelOtherItem; // here I get the expected value
});
res.status(201);
res.json({
item: item, // has a value
otherItem: modelOtherItem // -> is undefined
});
});
Promises立即返回,但它们的then
回调异步执行。这意味着您正在访问modelOtherItem
,然后才为其分配值。最简单的修复方法是在then
回调中添加代码(也可以去掉modelOtherItem
变量):
post(function (req, res) {
// ...
Item.create(data)
.then(function (item) {
OtherItem.create({
// ...
}).then(function (otherItem){
// add code here
res.status(201);
res.json({
item: item, // has a value
otherItem: otherItem // also has value
});
});
});
需要注意的一点是,通过将数组传递给Model.collection.insert(array...
,或者如果使用Mongoose,则可以通过Model.create(array...
,通过一次调用创建所有项目
替代解决方案
如果您的模型可以相互独立地创建(这意味着任何项目的创建都不依赖于任何其他项目),那么您可以使用Promise.all方法,该方法接受一个Promise数组,并在该数组中的所有Promise也解析后解析:
post(function (req, res) {
// ...
// create an array that will hold item creation promises
let promises = [];
// add the promise that creates the item
promises.push(Item.create(...));
// add the promise that creates the other item
promises.push(OtherItem.create(...));
Promise.all(promises)
.then(function(results) { // this function is called once all promises in the array `promises` resolve
// results contains the resolved data from each promises in the array
// in the order of the promises
var item = results[0];
var otherItem = results[1];
// OR you can use ES6 `let` declaration with
// destructuring to achieve the same as above
// in a cleaner way:
// let [item, otherItem] = results;
res.status(201);
res.json({
item: item,
otherItem: otherItem
});
// in ES6, if both the object property name and the variable name are the same
// you can just specify the name once and achieve the same effect as above
// with less code:
/*
res.json({
item,
otherItem
});
*/
});
});
相关文章:
- 收集订阅者的流星事件,用于在 mongodb 中新插入文档
- 谷歌应用程序脚本:如何修复循环将一个谷歌文档的段落插入另一个
- 在post请求中使用mongodb插入多个文档
- 如何使用vanillaJS将mp4视频插入到具有特定维度的html文档中,播放2秒,然后删除节点
- 追加到文档中尚未插入的新节点
- 在流星集合文档中插入值
- 通过node-js脚本将文档数组插入mongodb中的数据库时出现问题
- MongoDB在将文档插入数据库之前为空集合
- 使用 mongoDB 插入子文档
- 如果子文档值不存在,则 Mongo DB 插入到子文档中
- 创建猫鼬模式并插入文档
- 我正在尝试遍历 id 数组,如果不存在 id,则插入一个 mongodb 文档.我怎样才能让他们坚持下去
- 通过angularjs在mongodb中插入嵌入式文档
- Mongodb 节点.js获取插入文档的计数
- 使用mongoose和node.js在mongoDB中插入文档时遇到问题
- 如何存储HTML片段并稍后将其插入文档中
- 插入文档的动态iframe为标准模式,默认为怪僻模式
- mongo/ monid批量插入文档的MapReduce
- MongoDB / Node.JS:在循环中插入文档-变量不更新
- 在 NodeJS 中获取 Mongo 数据库中插入文档的_id