node.js - Mongoose Populate 返回一些空对象

标签 node.js mongodb mongoose

我有 1 个主要集合和 1 个带有主集合引用的集合。代码如下:

// Ref schema
    const onlineSchema = mongoose.Schema({
        _id: {
            type: Number,
            ref: 'Player',
            unique: true
        }
    }, {
        timestamps: true
    });

//main schema

const playerSchema = mongoose.Schema({

_id: { // User ID
    type: Number,
    required: true,
    unique: true,
    default: 0
},
firstname: {
    type: String
},
name: {
    type: String,
    required: true
},
lastname: {
    type: String
},
barfoo: {
   type: Boolean
}
...

})

我用以下代码填充它:

var baz = bar;
...
        Online.find().populate({
            path: '_id',
            match: {
                [ baz + 'foo']: true
            }
        }).exec(function(err, online) {
            if (err) {
                winston.error(err);
            } else {
                winston.error(util.inspect(online, {
                    showHidden: false,
                    depth: null
                }));

            }
        });

如果在线中有 10 个元素,并且只有 7 个匹配 [ baz + 'foo']: true 我会得到 7 个正确的数组和 3 个空数组,如下所示:

    { updatedAt: 2016-12-23T18:00:32.725Z,
createdAt: 2016-12-23T18:00:32.725Z,
_id: null,
 __v: 0 },

为什么会发生这种情况以及如何过滤最终结果以使其仅显示匹配的元素?

在获得结果后,我可以使用过滤器删除空数组,但我想知道如何防止查询首先传递空数组。

最佳答案

Why is this happening ?

发生这种情况是因为您使用 Online.find() 获取了所有文档,但 player 将仅填充符合您条件的记录。您的 match 用于 populate,而不是用于 find() 查询。

How do I filter the final result so it only shows the matching elements ?

由于 MongoDB 中没有联接,因此您无法找到引用集合的嵌套元素。但你可以:

  • 保留架构并使用 $lookup 进行聚合:

    Online.aggregate(
        [{
            $lookup: {
                from: "players",
                localField: "_id",
                foreignField: "_id",
                as: "players"
            }
        }, {
            $unwind: "$players"
        }, {
            $match: {
                'players.barfoo': true
            }
        }],
        function(err, result) {
            console.log(result);
        });
    
  • 更改架构以将 Player 包含为子文档:

    const playerSchema = new mongoose.Schema({
        //...
    });
    
    const onlineSchema = new mongoose.Schema({
        player: playerSchema
    }, {
        timestamps: true
    });
    
    var Online = mongoose.model('Online', onlineSchema);
    
    Online.find({'player.barfoo':true}).exec(function(err, online) {
        console.log(online);
    });
    

关于node.js - Mongoose Populate 返回一些空对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41306358/

相关文章:

node.js - 没有 knex 的书架 - 执行查询

javascript - 如何使 `winston` 日志库像 `console.log` 一样工作?

mongodb - Doctrine MongoDB ODM 的原子操作

java - MongoDB DBRef 列表在 Spring Boot 中返回 null

javascript - 如何执行find中的函数或将数据保存在变量中?

node.js - 具有随机键但字符串类型的对象的 Mongoose 模式

node.js - 从 Firebase Cloud Function 连接到 Stripe 时出错

MongoDB Map/Reduce Array 聚合问题

javascript - Mongoose 在更新时对多个字段进行自定义验证

node.js - 如何验证 Mongoose Schema 中的对象键和值?