对于猫鼬你可能可以做一个Promise.all() https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise/all并使用.concat() https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat?v=example在每个查询的结果数组上。
作为完整的演示:
var async = require('async'),
mongoose = require('mongoose'),
Schema = mongoose.Schema;
var d1Schema = new Schema({ "name": String });
var Data1 = mongoose.model("Data1", d1Schema);
var d2Schema = new Schema({ "title": String });
var Data2 = mongoose.model("Data2", d2Schema);
mongoose.set('debug',true);
mongoose.connect('mongodb://localhost/test');
async.series(
[
// Clean
function(callback) {
async.each([Data1,Data2],function(model,callback) {
model.remove({},callback)
},callback);
},
// Setup some data
function(callback) {
async.each([
{ "name": "Bill", "model": "Data1" },
{ "title": "Something", "model": "Data2" }
],function(data,callback) {
var model = data.model;
delete data.model;
mongoose.model(model).create(data,callback);
},callback);
},
// Actual Promise.all demo
function(callback) {
Promise.all([
Data1.find().exec(),
Data2.find().exec()
]).then(function(result) {
console.log([].concat.apply([],result));
callback()
}).catch(callback);
}
],
function(err) {
if (err) throw err;
mongoose.disconnect();
}
)
我只是混进去async https://caolan.github.io/async/docs.html为了简洁起见,但它的核心内容是:
Promise.all([
Data1.find().exec(),
Data2.find().exec()
]).then(function(result) {
console.log([].concat.apply([],result));
})
哪里的Promise.all()
基本上等待并组合两个结果,这将是一个“数组的数组”,但是.concat()
照顾这个。结果将是:
[
{ _id: 59420fd33d48fa0a490247c8, name: 'Bill', __v: 0 },
{ _id: 59420fd43d48fa0a490247c9, title: 'Something', __v: 0 }
]
显示每个集合中的对象,这些对象连接在一个数组中。
您还可以使用async.concat https://caolan.github.io/async/docs.html#concat方法作为替代方法,但除非您已经在使用该库,否则最好坚持承诺。