Node.js 节点mongoose:聚合未给出预期结果
使用以下组架构 group.model.jsNode.js 节点mongoose:聚合未给出预期结果,node.js,mongoose,Node.js,Mongoose,使用以下组架构 group.model.js const Role = new mongoose.Schema({ name: { type: String, required: true }, // ensure uniqueness withn group instance using addToSet description: { type: String, required: false } }); const GroupSchema = new mongoose.Schema
const Role = new mongoose.Schema({
name: { type: String, required: true }, // ensure uniqueness withn group instance using addToSet
description: { type: String, required: false }
});
const GroupSchema = new mongoose.Schema({
name: { type: String, index: { unique: true, required: true, dropDups: true } },
description: { type: String, required: false },
roles: [Role],
createdAt: {
type: Date,
default: Date.now
}
});
我试图列出所有角色(子文档)的特定组
group.controller.js
function listRoles(req, res) {
const group = req.group;
console.log('GROUP: %j', group);
const limit = parseInt(req.query.limit, 10) || 50;
const skip = parseInt(req.query.skip, 10) || 0;
Group.aggregate([
{ $match: { _id: req.params.groupId } },
{ $unwind: '$roles' },
{ $skip: skip },
{ $limit: limit }
], (err, result) => {
if (err) {
res.status(500);
res.json({ message: 'Error. Cannot list roles', errror: err });
}
res.status(200);
console.log('RESULT: %j', result);
res.json(result);
});
}
我应该得到一个只有一个角色的数组,但是我得到一个空数组
我的聚合代码有什么问题?谢谢你的反馈
注意:我试图仅使用管道中的$match进行聚合,并且还得到一个空数组。。。所以我想。问题来自req.params.groupId应为ObjectId。。我该怎么投
控制台日志
GROUP: {"_id":"5923e2e83afd4149bdf16c61","name":"Admin","description":"Administration group","__v":1,"createdAt":"2017-05-23T07:21:12.470Z","roles":[{"name":"Role1","description":"description role1","_id":"5923e2e83afd4149bdf16c62"}]}
RESULT: []
为了更好地诊断这个问题,我建议删除聚合管道中的步骤,看看结果如何。但是,我怀疑您的问题是因为您在第一阶段没有匹配项,因为您正在将字符串与
ObjectId
进行比较。试试这个:
const mongoose = require('mongoose')
// and in the aggregation:
{ $match: { _id: mongoose.Types.ObjectId(req.params.groupId) } }
像这样运行mongod:
mongo-vvv
并查看您的程序正在进行何种查询。问题似乎与以下事实有关:我正在使用req.params.groupId作为匹配中的_id的值,它是一个字符串。。。而不是一个ObjectId。。我能投吗?看一看:谢谢,这就是我怀疑的。。。实际上,我没有想到“比较”。。。这是我第一次使用聚合,我认为猫是自动执行的。。。谢谢,第一次真是太令人惊讶了!FWIW如果在JS中比较ObjectId
s,则需要使用ObjectId.equals(ObjectDB)
作为ObjectId==ObjectDB
始终返回false
,即使它们看起来相同。我第一次浪费了两个小时。。。