如何在人口密集的mongoose.methods中获取数组元素?

时间:2017-08-28 22:42:32

标签: javascript express mongoose

我需要从mongoose.methods回调中获取数组的元素(或第一个元素)

  { _id: 5994e4157aca6a0bb5e911e8,
   username: 'user1',
   roles:
    { account:
       { _id: 5994c2dbacd0b30b6f5bae90,
         groups: [Object] }      // need to get elements of this array

方法

  userSchema.methods.accountGroupOfUser = function accountGroupOfUser(callback) {
    return mongoose.model('User', userSchema)
      .findById(this.id)
      .populate( {path: 'roles.account', model: 'Account', select: 'groups'} )
      .exec(function(err, user) {
        if (err) {
          return callback(err, null);
        }
        return callback(null, user);
      });
  };

因此,它获取了主User文档,并从引用的groups文档填充Account字段。 我想在Express中间件中使用此字段,并在回调中获取它

app.use(function(req, res, next) {
  res.locals.user = {};
  res.locals.user.accountGroupOfUser = req.user && req.user.accountGroupOfUser(function(err, user) {
    if (err) {
      return (err);
    }
    // Here is where I'm trying to get the items
    return (user.roles.account.groups.forEach(function (err, item) {
      return (item); // not working
      // return (user.roles.account.groups[0]) not worikng too
    }));
  });
  next();
});

当您进行常规查询并在模板中使用它时,调用user.roles.account.groups[0]会返回一个值,但不会在mongoose.methods的回调中工作,并且始终返回[object Object]而不是实际值。 我只需要获取必须存储在accountGroupOfUser中的值,如何在回调中获取它?

更新

模式

  // user -> roles.account ref to Account model 
  var userSchema = new mongoose.Schema({
    // ...
    roles: {
      account: { type: mongoose.Schema.Types.ObjectId, ref: 'Account' }, 
    },
 });

  // account -> ref to AccountGroup
  var accountSchema= new mongoose.Schema({
    // ...
    groups: [{ type: String, ref: 'AccountGroup' }], 
  });

  // accountGroup -> is populated in account.groups
exports = module.exports = function(app, mongoose) {
  var accountGroupSchema = new mongoose.Schema({
    _id: { type: String },  // slugified name of a group can use this as group name too
    name: { type: String, default: '' },  // group name
    permissions: [{ name: String, permit: Boolean }]
  });

0 个答案:

没有答案