node.js - Mongodb $lookup 不使用 _id

标签 node.js mongodb mongoose

尝试使用此查询,返回查找为空

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/

相关文章:

javascript - 子进程 spawn 在 Electron 中产生 TypeError "stdout.on is not a function"

javascript - 如何在 node.js 中导出 env 变量

javascript - 如何将一些 API 数据从 v-for 循环保存到我的 mongodb?

node.js - 在一个 mongoose 查询中从 2 个独立的 Mongo 文档获取信息

javascript - 编写一个函数来计算 Node 和浏览器中的执行时间?

json - 避免使用node.js在rest api中进行缓存

asp.net - 在 Windows 上托管进程内文档数据库

mongodb - 按匹配元素数量的顺序查询 MongoDB 中数组中包含的元素

mongodb - 使用 MongoDB API 连接到 CosmosDB 时出现超时错误

javascript - Mongoose 按数组条目 ($in) 进行搜索的行为与 MongoDB Atlas 不一致