Tuesday, 23 May 2017

node mongoose : aggregate not giving expected result

withe the following Group 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
  }
});

I am trying to list all roles ( subdocument) got a specific group

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);
  });
}

I should get an array with one role, but I get an empty array what's wrong with my aggregate code ? thanks for feedback

note: I tried to aggregate only with the $match in the pipe and I also get an empty array...

console.log

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: []



via erwin

No comments:

Post a Comment