【问题标题】:Remove document from results if in different collection如果在不同的集合中,从结果中删除文档
【发布时间】:2017-11-03 09:19:13
【问题描述】:

我有分配、签入和资产集合,当我转到 /assign 页面时,我运行以下查询:

Asset.find({"author.id":req.user.id}, function(err, allAsset) {
        if(err){
          console.log(err);
        } else {
          res.locals.assets = allAsset; // Set the data in locals
          next();
        }
      });

查找登录用户拥有的所有资产。我想要它,以便如果 asset 已经分配,​​它将无法再次分配。来自 mongodb 的已分配资产的示例文档是:

    { "_id" : ObjectId("59fb2cdb02b2a83502cd0df6"),
     "subuser" : "Kirbytech",
     "checkoutDate" : "2017-12-30",
     "notes" : "241361",
     "author" : { 
       "id" : ObjectId("59d7f98a77fcc221d6e3c93d"), 
       "email" : "joe@example.com.ca" 
     }, "asset" : {
       "id" : "59f7cde58a6f9b11e1cd07d9",
       "num" : 1005 
     },
     "__v" : 0 }

我看到了this,但对我帮助不大。我知道我需要搜索找到或未找到 asset.id 的所有文档(不确定是哪个),然后将这些结果保存到 res.locals.assets

我当然希望这是有道理的。如果需要,请要求澄清。

【问题讨论】:

    标签: mongodb mongoose


    【解决方案1】:

    能否查询带有user_id和asset_id的Assign集合,如果返回值为null,则该asset还没有被赋值。

    我假设在资产“分配”给用户时创建了已分配记录。

    Assign.find({}, function(err, assignedRecords){
     // this will be an array of all assigned assets
     let allAssignedAssets = assignedRecords.map((doc) =>doc.asset.id)
     // now get all the assets not in the above array
       Asset.find({id:{$nin: allAssignedAssets}}, function(err, allUnassignedAssets) {
         if(err){
          console.log(err);
         } else {
          res.locals.assets = allUnassignedAssets; // all unassigned assets
          next();
       }
     } 
    })
    

    如果您需要更多说明,请告诉我。

    【讨论】:

      猜你喜欢
      • 2021-11-14
      • 2017-03-15
      • 2021-11-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多