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": []
}
]
我尝试了这篇文章,但没有发生MongoDB将项目字符串聚合到ObjectId和这个MongoDB$lookup在PHP中使用_id作为foreignField
更新
这是文档“用户”
{
"_id" : ObjectId("549e0bb67371ecc804ad24ef"),
"displayname" : "Jhon S."
},
{
"_id" : ObjectId("549e0bb67371ecc804ad21ef"),
"displayname" : "George F."
},
{
"_id" : ObjectId("549e0bb67371ecc804ad23ef"),
"displayname" : "Franc D."
}
我最终找到了解决方案,是我在mongoose中使用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},
});
正在工作
首先,断言incharge
字段的类型为mongoose.schema.types.objectid
。如果仍然返回空数组,可能是因为您使用了在NodeJS中声明的模式名,而不是MongoDB使用的集合名。
userschema
文件中的示例:
const mongoose = require('mongoose')
const Schema = mongoose.Schema
const UserSchema = new Schema({
name: {
type: String,
required: true
},
incharge: {
type: Schema.Types.ObjectId,
required: true
},
})
const User = mongoose.model('User', UserSchema)
module.exports = User
上面的模型由mongoose命名为user
,但mongoDB中的相应集合命名为users
。结果的$lookup
写成:
$lookup:{
from: "users", // name of mongoDB collection, NOT mongoose model
localField: "incharge", // referenced users _id in the tests collection
foreignField: "_id", // _id from users
as: "user" // output array in returned object
}
https://mongoosejs.com/docs/models.html
https://mongoosejs.com/docs/schematypes.html