如何从两个不同的集合中获取记录

时间:2017-12-30 09:23:46

标签: node.js mongodb mongoose lookup

我正在尝试从两个不同的集合中获取记录,但是当我从一个集合中获取结果并且匹配的数组变空时。

var data = mongoose.Schema({
    user_id:{type:String},
    coin_key:{type:String},
    address:{type:String},
    label:{type:String}
});

var coin_info = new mongoose.Schema({
    _id: mongoose.Schema.Types.ObjectId,
    wallet_name:{type:String},
});

var deposte_model = mongoose.model('deposit',data);

var get_coin_info = mongoose.model('coin_infos',coin_info);

deposte_model.aggregate([
    {
        $lookup: {
            from: 'get_coin_info',
            localField: 'coin_key',
            foreignField: '_id',
            as: 'orderdetails'
        }
    }
]).exec(function(err, res) {
    if (err) throw err;
    console.log(res);
});

结果如下:

[{ 
    _id: 5a448ca723df911015711d8c,
    user_id: '5a3e432e42850631fceeda8e',
    coin_key: '5a43634fabe09f65ddf75c0c',
    label: 'test',
    address: '1QLVovgdv8PrnSXfLD2J5YS2eKVKekGkTK',
    __v: 0,
    orderdetails: [] 
}],

1 个答案:

答案 0 :(得分:0)

$ lookup from应该是MongoDB中的集合名称。在您的情况下' coin_info'不是' get_coin_info'。这有帮助吗?

此外,如果你愿意做得更好,我建议你学习MongoDB填充。 http://mongoosejs.com/docs/populate.html