我一直在寻找一种方法来轻松获得 mongoose js 的结果,只需编写如上所示的查询即可:
Article.find().skip(data.skip)
如果我想添加另一个查询,只需输入查询即可:
Article.find().skip(data.skip)
Users.find().skip(data.skip),
因此,为了获得组织,我将此查询放入一个带有她的键的对象中:
Articles: Article.find().skip(data.skip),
Users: Users.find().skip(data.skip),
接下来,我将能够通过这种方式使用 asyncjs 对其进行解析:
function process (obj, next) {
console.log(obj.length);
asyncjs.mapValues(obj, function(query, key, callback) {
query.exec(function(err, results) {
callback(results, key)
});
}, next)
}
因此,我希望在调用 next 时得到 asyncjs 文档中所说的结果:
async.mapValues({
f1: 'file1',
f2: 'file2',
f3: 'file3'
}, function (file, key, callback) {
fs.stat(file, callback);
}, function(err, result) {
// result is now a map of stats for each file, e.g.
// {
// f1: [stats for file1],
// f2: [stats for file2],
// f3: [stats for file3]
// }
});
但事实并非如此,我只是得到了第一个查询的结果,这是完整的 javascript 表:
var mongoose = require('mongoose');
var asyncjs = require('async');
var app = require('express')();
mongoose.connect('mongodb://localhost/adifia');
mongoose.Promise = global.Promise;
var articlesScheme = new mongoose.Schema({
title: String,
state: String,
content: String,
author: String,
permisionLVL: Number,
created_at: Date
});
var usersScheme = new mongoose.Schema({
name: String,
email: String,
password: String,
age: Number,
banned: Boolean
});
var Article = mongoose.model('Article', articlesScheme);
var Users = mongoose.model('User', usersScheme);
// Encontrar la menera de utilizando una funcion de async poder ejecutar dos consultas de mongoose y guardar los resultados en una variable
function process (obj, next) {
console.log(obj.length);
asyncjs.mapValues(obj, function(query, key, callback) {
query.exec(function(err, results) {
callback(results, key)
});
}, next)
}
function action(data, process, next) {
var queries = {
Articles: Article.find().skip(data.skip),
Users: Users.find().skip(data.skip),
};
process(queries, next);
}
var query = {
limit: 1
}
action(query, process, function(err, results) {
console.log(err);
})
undefined
[ { _id: 58498848e938264fcfda298e,
title: 'bieeen',
content: 'yupiiiiaa',
author: null,
created_at: 2016-12-08T16:20:24.688Z,
state: 'draft',
__v: 0 },
{ _id: 58498848e938263fcfda298e,
title: 'bien',
content: 'yupiiaa',
author: null,
created_at: 2016-12-08T16:20:24.688Z,
state: 'draft',
__v: 0 } ]
最佳答案
请注意,async.mapValues
的回调预计将使用 Node.js 约定调用:err
作为第一个参数,res
作为第二个。你这样调用它:
callback(results, key)
因此,如果 results
不是假的,async 就不会在下一个值上调用您的函数。如果没有错误,调用 callback
并返回一个错误值(约定为 null
)
关于javascript - 使用 async.js mapValues 获取部分结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41085417/