0

我有一个相当简单的集合:

var Access = new Schema({
  userId         : { type: ObjectId, index: true },
  token          : { type: String, index: true },
  isOwner        : { type: Boolean, index: true },
});
mongoose.model('Access', Access);

var Workspace = new Schema({
  name           : { type: String, lowercase: true, unique: true},
  description    : String,
  isActive       : Boolean,
  settings       : {
    longName        : String,
    welcomeMessage  : String,
    countryId       : { type: ObjectId, index: true },
  },
  access          : [ Access ],
});
mongoose.model('Workspace', Workspace);

当用户连接时,我有一个中间件检查令牌并查看是否一切正常。所以我有:

exports.tokenCall = function( req, res, next, token ){

  var Workspace = mongoose.model('Workspace'),
      User = mongoose.model('User'),
      accessEntry;

  req.application = {};

  // Find the token
  Workspace.findOne({ 'access.token': token } , function(err, doc){
    if(err){
      next( new g.errors.RuntimeError503( err ) );
    } else {
      if(! doc ){
        next( new g.errors.BadtokenError403() );
      } else {
        accessEntry = doc.access.filter(function(entry){ return entry.token == token;  } )[0];

        req.application.workspaceId = doc._id;
        req.application.workspaceName = doc.name;
        req.application.userId = accessEntry.userId;
        req.application.login =  accessEntry.login;
        req.application.token = token;
        req.application.workspace = doc; // Contains all of the settings!
        next();
      }
    }
  });
}

我相信您可以在这里看到我的问题:我运行Workspace.findOne({ 'access.token': token } , function(err, doc){以找到具有正确标记的文档。但是,然后,我实际上...搜索一个数组(!)以找到我寻找的实际令牌!accessEntry = doc.access.filter(function(entry){ return entry.token == token; } )[0];我确信这不是这样做的方法——当然。如果我向下查询 4 ​​级怎么办...?!?

那么,这样做的正确方法是什么?

4

1 回答 1

1

如果您使用的是 Mongo 2.2,您可以利用新的$elemMatch投影运算符仅access在返回的文档中包含匹配的数组元素:

Workspace.findOne(
    { 'access.token': token }, 
    { _id: 1, name: 1, access: { $elemMatch: { token: token } } },
    function(err, doc) {
        // doc contains _id, name, and only the access array elements that match on token
于 2012-08-31T04:10:54.347 回答