javascript - 通过 Mongoose (MongoDB) 中的嵌入引用数组查找文档

标签 javascript node.js mongodb mongoose mongodb-query

假设我有以下集合架构

var terminalSchema = new mongoose.Schema({
    name: 'String', 
    ip: 'String'
});

var wayPointSchema = new mongoose.Schema({
    name: 'String',
    description: 'String',
    long: 'Number',
    lat: 'Number',
    distances: [{
        toTerminal : { type: Schema.Types.ObjectId, ref: 'Terminal' },
        km : 'Number',
        minutes: 'Number'
    }]
});

如何找到所有带有terminal.ip = '10.0.0.1'的WayPoint

我尝试了以下方法,但没有成功......

WayPoint.find()
.populate({
    path: 'distances.toTerminal',
    match:  { 'distances.toTerminal.ip': '10.0.0.1'},
})
.exec(function(err, wp) {
    if(err || !wp) {
          throw err;
        } else {
          console.log(wp);
        }
})

返回整个集合

更新 - 进度?

我认为我已经使用以下代码取得了一些进展,因为它现在仅显示用于匹配子文档的 [object] 和用于匹配子文档的 null不匹配。

WayPoint.find({'distances.toTerminal': {$exists: true}})
.populate({
    path: 'distances.toTerminal',
    select: 'description',
    match:  { ip: '10.0.0.1'}
})
.exec(function(err, wp) {
    if(err || !wp) {
          throw err;
        } else {
          console.log(wp);
        }
})

最佳答案

这里.populate()的“匹配”部分实际上并不是来自“WayPoint”对象的“完整”可视化路径,而实际上仅适用于“Terminal”对象。 “WayPoint”只有引用,因此您可以这样做:

WayPoint.find()
    .populate({
        "path": "distances.toTerminal",
        "match": { "ip": "10.0.0.1" }
    })
    .exec(function(err,wp) {
        if (err) throw err;  // or otherwise handle

        wp = wp.filter(function(doc) {
            doc.distances = doc.distances.filter(function(distance) {
                return distance.toTerminal != null;
            });
            return doc.distances.length > 0;
        });

        console.dir(wp);
    });

这确实不是通过“终端”ip 值查找“WayPoint”的非常有效的方法,因为 mongoose 实际上会获取所有“WayPoint”项目,并且您必须自己“过滤”才能找到匹配的项目.

更好的方法是“嵌入”文档,然后您可以发出顶级查询来仅查找匹配的文档:

WayPoint.find({ "distances.toTerminal.ip": "10.0.0.1" },function(err,wp) {

这是一般的 MongoDB 方式,但如果您不能这样做或者不切实际,那么您最好找到匹配的“终端”对象的 _id 并将其传递给到您的“WayPoint”查询。 “异步”库对清理代码的一点帮助:

async.waterfall(
    [
        function(callback) {
            Terminal.find({ "ip": "10.0.0.1" },function(err,terms) {
                if (err) throw err;
                ids = terms.map(function(term) { return term._id; });
                callback(err,ids);
            });
        },

        function(ids,callback) {
            WayPoint.find(
               { "distances.toTerminal": { "$in": ids } },
               function(err,wp) {
                   if (err) throw err;
                   console.dir( wp );
                   callback();
               }
            );
        }
    ]
);

关于javascript - 通过 Mongoose (MongoDB) 中的嵌入引用数组查找文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24846614/

相关文章:

angularjs - IBM推送: cannot use sendNotificationByDeviceIds in ibmpush. js

javascript - 在开发者控制台的“网络”选项卡上访问或获取文件

javascript - Sequelize JS - 保护属性

javascript - Nodejs 页面渲染时未加载

mongodb - 如何过滤子文档数组?

node.js - 使用express和mongo在mongodb中保存复杂的结构

javascript - .removeAttr ('style' ) 在 ipad 上似乎无法正常工作

javascript - tableexport 插件给出 Uncaught TypeError : o is not a function

javascript - 在 Javascript 中,给定值,从对象文字中查找名称

javascript - "Failed to execute 'appendChild' on 'Node'”是什么意思?