node.js - 想在mongodb node.JS中通过_id获取引用集合的对象

标签 node.js mongodb mongoose mongodb-query aggregation-framework

我想通过引用 id 集合获取特定记录的所有详细信息。

{
"_id" : ObjectId("586c8bf63ef8480af89e94ca"),
"createdDate" : ISODate("2017-01-04T05:45:26.945Z"),
"branch" : {
    "$ref" : "branchmst",
    "$id" : "5864ac80fa769f09a4881791",
    "$db" : "eviral"
    },
"__v" : 0
}

这是我的收藏记录。我需要“branchmst”集合中的所有详细信息,其中“_id”是“5864ac80fa769f09a4881791”。

最佳答案

您的收藏是使用手动引用的示例,即在另一个文档中包含一个文档的 _id 字段 DBref .然后 Mongoose 可以发出第二个查询以根据需要解析引用的字段。

第二个查询是使用具有 $lookup 的聚合方法 运算符将对同一数据库中的“branchmst”集合执行左外连接,以过滤来自“已连接”集合的文档以进行处理:

MyModel.aggregate([
    { "$match": { "branch": "5864ac80fa769f09a4881791" } },
    {
        "$lookup": {
            "from": "branchmst",
            "localField": "branch",
            "foreignField": "_id",
            "as": "branchmst"
        }
    },
    { "$unwind": "$branchmst" }
])

您还可以使用 populate() Mongoose 中的函数,因为您已经在模型定义中明确定义了引用,即

var mongoose = require('mongoose');
var ObjectId = mongoose.Schema.Types.ObjectId;

// define the main schema
var mySchema = mongoose.Schema({
    createdDate: { type: Date, default: Date.now },
    branch: { type: ObjectId, ref: 'Branch' }  
})

// define the branch schema
var branchSchema = mongoose.Schema({
    name: String,
    address: String  
})

// compile the models
var MyModel = mongoose.model('MyModel', mySchema),
    Branch = mongoose.model('Branch', branchSchema);

// populate query
MyModel.find({ "branch": "5864ac80fa769f09a4881791" })
       .populate('branch')
       .exec(function (err, docs) {
           //console.log(docs[0].branch.name);
           console.log(docs);
       });

关于node.js - 想在mongodb node.JS中通过_id获取引用集合的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41484249/

相关文章:

node.js - 错误 TS2305 : Module has no exported member

Mongodb: `com.mongodb.MongoSocketReadException: Prematurely reached end of stream` 与吗啡

MongoDB - 如何在 Mongoose 中为一个字段定义多个数据类型?

c - Mongoose 中的 mg_send_response_line() 不起作用

node.js - Mongoose .find 字符串参数

javascript - 来自nodeJS脚本的python shell向nodejs返回相同的值

javascript - 使用express包和EJS模板引擎在node.js服务器上的两个网页之间建立href链接

javascript - NODEJS 和 mysql-node 并且没有数据库更改

Mongodb查询可变数量的搜索词

mongodb - Symfony 2.1 + @MongoDBUnique(字段 ="email") 不唯一