Mongo Aggregate返回没有数组

时间:2017-03-03 13:57:37

标签: node.js mongodb mongoose

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

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: [] }

怎么做?

1 个答案:

答案 0 :(得分:0)

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

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);
});

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

相关问题