【问题标题】:Mongo Aggregate return without arrayMongo聚合返回没有数组
【发布时间】:2017-03-04 00:05:33
【问题描述】:

我有一个数据库查询,它连接两个表并将结果作为一个数组返回,但我不能超过一个元素和我不需要的数组:

Model.aggregate([
{
    $lookup: {
        from: 'translations',
        localField: '_id',
        foreignField: 'item_id',
        as: 'translation'
    },
}, 
{
    $project: {
        "label": 1, 
        "items": 1,
        "translation": {

        }
    }
}], function(err, data) {
    callback(err, data);
})

我的结果:

[ { _id: 58b95bad4321200de3f61a31,
label: 'BLUECHIPS',
items: [],
translation: [] } ]

我想要没有数组的结果,例如:

{ _id: 58b95bad4321200de3f61a31,
label: 'BLUECHIPS',
items: [],
translation: [] }

这是怎么做到的?

【问题讨论】:

  • 您是否尝试将数据返回为callback(err, data[0]);
  • 我知道)))) 但我的问题是如何在没有数组的情况下接收结果?
  • 您使用返回第一个元素,如上述评论者建议的那样。您无法更改库返回的内容,但您可以随意映射它。

标签: node.js mongodb mongoose


【解决方案1】:

您可以为模型添加一个新的静态方法来满足您的需要。

Model.statics.aggregateOne = function aggregateOne(array, cb) {
  this.aggregate(array, (err, data) => {
    if (err) return cb(err);
    cb(data[0]);
  });
}

您现在应该可以用作:

Model.aggregateOne([
{
    $lookup: {
        from: 'translations',
        localField: '_id',
        foreignField: 'item_id',
        as: 'translation'
    },
}, 
{
    $project: {
        "label": 1, 
        "items": 1,
        "translation": {

        }
    }
}], function(err, data) {
    callback(err, data);
});

与您发布的代码相同,只是方法名称不同。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-06-25
    • 1970-01-01
    • 2021-09-05
    • 2020-05-02
    • 2021-11-24
    • 2021-01-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多