【问题标题】:How to fetch record from two different collection如何从两个不同的集合中获取记录
【发布时间】:2018-06-10 11:37:33
【问题描述】:

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

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

【问题讨论】:

    标签: node.js mongodb mongoose lookup


    【解决方案1】:

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

    另外,如果您愿意让它变得更好,我建议您了解 MongoDB 填充。 http://mongoosejs.com/docs/populate.html

    【讨论】:

    • 我按照你说的做了,但没有得到输出。
    • mongoose.model('coin_infos',coin_info); 也应该是mongoose.model('coin_info',coin_info);
    • 我正在尝试使用终端,但也得到了空数组。
    • db.deposits.aggregate([{ $lookup: { from: 'coin_infos', localField: 'coin_key', foreignField: '_id', as: 'user' } }]).pretty( ); {“_ID”:ObjectiD(“5A4B0F4A32C51230087A5453”),“User_ID”:“5A4B0787A0050C20A6BE44B2”,“COIN_KEY”:“5A4B07B2A0050C20A6BE44B3”,“标签”:“测试”,“测试”,“ADDRY”:“17DHDZSOABADME6M9WBNQS4N6WU3YCJM”,“__V”:0, “用户”:[]} {“_ID”:ObjectID(“5A4B0F7CE170A030CA189FDD”),“User_ID”:“5A4B0787A0050C20A6BE44B2”,“COIN_KEY”:“5A4B07B2A0050C20A6BE44B3”,“标签”:“TEST2”,“地址”:“1KUTOFZ5TCPZENVKORS4XXTQ8H” , "__v" : 0, "用户" : [ ] }
    猜你喜欢
    • 2016-12-01
    • 2018-06-27
    • 1970-01-01
    • 2022-10-12
    • 2015-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-09
    相关资源
    最近更新 更多