mongoose填充返回一些空的对象
我有1个主要collections品和1个collections品以及主要collections品。 代码如下所示:
// 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 },
为什么会发生这种情况,以及如何筛选最终结果,只显示匹配的元素?
我可以使用筛选删除空数组后,我得到的结果,但我想知道如何防止查询首先传递空数组。
为什么发生这种情况?
这是因为你使用Online.find()
获得了所有文档,但是只有符合条件的logging才会填充player
。 您的match
是为了populate
,而不是find()
查询。
如何筛选最终结果,只显示匹配的元素?
你不能find一个引用集合的嵌套元素,因为在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); });
不要使_id
作为另一个模式的reference
,而是使另一个field
名称player
并通过该reference
。
const onlineSchema = mongoose.Schema({ player: { type: Number, ref: 'Player', unique: true } }, { timestamps: true });
人口:
Online.find().populate({ path: 'player', match: { [ baz + 'foo']: true } }).exec(...);
不要使用_id来引用字段..因为它的默认在mongoDB中创build索引唯一..更改你的字段名称