Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/37.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 节点mongoose:聚合未给出预期结果_Node.js_Mongoose - Fatal编程技术网

Node.js 节点mongoose:聚合未给出预期结果

Node.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

使用以下组架构

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({
  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
,即使它们看起来相同。我第一次浪费了两个小时。。。