2016-06-08 81 views
1

WEND不工作尝试与此查询,返回查询为空

db.getCollection('tests').aggregate([ 
    {$match: {typet:'Req'}}, 
    {$project: {incharge:1}}, 
    {$lookup:{ 
      from: "users", 
      localField: "incharge", //this is the _id user from tests 
      foreignField: "_id", //this is the _id from users 
      as: "user" 
    }} 
]) 

返回JSON

[ 
    { 
     "_id": "57565d2e45bd27b012fc4db9", 
     "incharge": "549e0bb67371ecc804ad23ef", 
     "user": [] 
    }, 
    { 
     "_id": "57565d2045bd27b012fc4cbb", 
     "incharge": "549e0bb67371ecc804ad21ef", 
     "user": [] 
    }, 
    { 
     "_id": "57565d2245bd27b012fc4cc7", 
     "incharge": "549e0bb67371ecc804ad24ef", 
     "user": [] 
    } 
] 

我试图用这个帖子,但没有happend MongoDB aggregation project string to ObjectId 与这 MongoDB $lookup with _id as a foreignField in PHP

UPDATE

这是文档 “用户”

{ 
     "_id" : ObjectId("549e0bb67371ecc804ad24ef"), 
     "displayname" : "Jhon S." 
    }, 
    { 
     "_id" : ObjectId("549e0bb67371ecc804ad21ef"), 
     "displayname" : "George F." 
    }, 
    { 
     "_id" : ObjectId("549e0bb67371ecc804ad23ef"), 
     "displayname" : "Franc D." 
    } 
+0

请发布文档示例,因为这将帮助我们帮助您:-) – profesor79

+0

感谢人添加文档用户 – JorgeFo

回答

4

我finaly找到了解决办法,是与我的猫鼬架构与的ObjectId

一个问题,我改变这个

var Schema = new Schema({ 
    name: { type: String, required: true}, 
    incharge: { type: String, required: true}, 
}); 

与此

var Schema = new Schema({ 
    name: { type: String, required: true}, 
    incharge: { type: mongoose.Schema.ObjectId, required: true}, 
}); 

并正在

+0

感谢您发布此信息,我遇到了完全相同的问题! – stackers

0

你查找查询是完美的,但问题是你存储incharge为串入分贝,而_id:物件(“theID”)是一个对象,而不仅仅是字符串和你无法将string('')与object({})进行比较。因此,最好的方法是将incharge密钥存储为对象(mongoose.Schema.ObjectId),而不是模式中的字符串。