【发布时间】:2018-08-22 07:58:36
【问题描述】:
我在 Node.js 中有以下代码:
exports.getProfiles = async function(query, page, limit, val){
var options = {
page,
limit
};
let clause = [
{$project:{name:{$concat:["$firstName"," ","$lastName"]}, docs: '$$ROOT' }},
{$match:{name:new RegExp(val, 'i')}}
];
function getProfileByFullName (callback) {
Profile.aggregate(clause, function (err, result) {
if (err)
return callback(err);
if (result.length)
return callback(null, result[0]);
})
};
try {
var profiles = await Profile.paginate(query, options);
console.log('after pagination: ');
console.log(profiles);
getProfileByFullName(function (err, res) {
profiles = res;
console.log('function call: ');
console.log(profiles);
});
console.log('after the function call: ');
console.log(profiles);
return profiles;
} catch (e) {
throw Error('Error while Paginating Profiles: ' + e);
}
}
这应该做的是根据用户(配置文件)部分或全名返回一个 mongo 文档列表。 mongo 文档将名称拆分并按 firstName 和 lastName 值存储:
var mongoose = require('mongoose');
var mongoosePaginate = require('mongoose-paginate');
var Schema = mongoose.Schema;
var UserProfileSchema = new mongoose.Schema({
firstName: {type: String, default: ''},
lastName: {type: String, default: ''},
dateOfBirth: {type: Date, default: null},
address: {type: String, default: ''},
maritalStatus: {type: String, default: ''},
contactPhone: {type: String, default: ''},
contactEmail: {type: String, default: ''},
gender: {type: String, default: ''},
occupation: {type: String, default: ''}
});
UserProfileSchema.plugin(mongoosePaginate)
const UserProfile = mongoose.model('UserProfile', UserProfileSchema)
module.exports = UserProfile;
我的问题是,当我尝试从聚合函数返回结果时,它不会返回任何东西。
结果不为空,当我通过 console.log 打印时,它会打印正确的文档。我从一个控制器调用这个函数,这个函数是从快速路由中调用的。
你们能帮帮我吗?
编辑:
输出是:
after pagination:
{ docs: [], total: 0, limit: 100, page: 1, pages: 1 }
after the function call:
{ docs: [], total: 0, limit: 100, page: 1, pages: 1 }
GET /api/profiles/search/?firstName=Tischler%20Krist%C3%B3f&lastName=Tischler%20Krist%C3%B3f 200 396.098 ms - 114
function call:
{ _id: 5a9cf0298e28e3773f19def1,
name: 'Tischler Kristóf',
docs:
{ _id: 5a9cf0298e28e3773f19def1,
occupation: 'Software Developer',
gender: 'Male',
contactEmail: 'asd@asd.com',
contactPhone: '+363083741246214',
maritalStatus: 'Single',
address: '64343 Valahol, Király utca 56.',
dateOfBirth: 1995-08-25T22:00:00.000Z,
lastName: 'Kristóf',
firstName: 'Tischler',
__v: 0 } }
编辑:
我已经更新了代码,因为我在 getProfileByFullName 函数中缺少回调参数。如您所见,我显然搞砸了,因为控制台日志出现故障,我想我在这里遗漏了一个关键的东西......
【问题讨论】:
-
你能添加日志吗??
-
好的,今晚回家后我会附上它们。
-
我已经更新了问题。
标签: node.js mongodb mongoose aggregate