【问题标题】:Mongoose return aggregate result like mongoose paginate猫鼬返回聚合结果,如猫鼬分页
【发布时间】: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


【解决方案1】:

好吧,看来我把事情复杂化了,而且很简单:

var profiles = await Profile.aggregate(clause);
return profiles;

然后修改,然后在其他地方返回值解决了我的问题。

【讨论】:

    【解决方案2】:

    如果我理解正确,您想要的是在返回的文档中执行一些操作,但在脚本中的其他位置执行。

    如果是这样,则需要声明一个数组,并将返回的每个文档推送到数组中,如下所示:

    var resultArray = [];               // Declare an array
    
    function getProfileByFullName () {
        Profile.aggregate(clause, function (err, result) {
              console.log('Inside the aggregate function: ');
              console.log(result);
            // How do I return the result from here, like the pagination below and store it in a variable???
            resultArray.push(result);   // Push into the array
        })
    };
    
    console.log(resultArray);           // Do stuff with the documents in the array
    

    【讨论】:

    • 这个解决方案没有解决我的问题,也许我不清楚。我已经更新了问题,以便您更好地理解它。
    猜你喜欢
    • 2015-08-04
    • 2017-03-30
    • 2014-05-30
    • 2017-12-03
    • 2015-08-26
    • 2020-04-26
    • 2012-09-20
    • 2015-05-19
    相关资源
    最近更新 更多