尝试使用此查询,返回查找为空
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": []
}
]
我尝试了这篇文章,但什么也没发生 MongoDB aggregation project string to ObjectId 有了这个 MongoDB $lookup with _id as a foreignField in PHP
更新
这是文档“用户”
{
"_id" : ObjectId("549e0bb67371ecc804ad24ef"),
"displayname" : "Jhon S."
},
{
"_id" : ObjectId("549e0bb67371ecc804ad21ef"),
"displayname" : "George F."
},
{
"_id" : ObjectId("549e0bb67371ecc804ad23ef"),
"displayname" : "Franc D."
}
最佳答案
我终于找到了解决方案,是我在 Mongoose 中使用 ObjectId 的 Schema 的问题
我改这个
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},
});
并且正在工作
关于node.js - Mongodb $lookup 不使用 _id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37705517/