Nodejs + mongodb:如何查询$ ref字段? [英] Nodejs + mongodb : How to query $ref fields?

查看:282
本文介绍了Nodejs + mongodb:如何查询$ ref字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用带有nodejs REST服务的MongoDB,它暴露了我存储在里面的数据。我有一个关于如何查询使用$ ref的数据的问题。

I'am using MongoDB with a nodejs REST service which exposes my data stored inside. I have a question about how to interrogate my data which uses $ref.

这是一个Object的示例,其中包含对其他对象(详细信息)的引用:

Here is a sample of an Object which contains a reference to another object (detail) in anther collection :

{
    "_id" : ObjectId("5962c7b53b6a02100a000085"),
    "Title" : "test",
    "detail" : {
        "$ref" : "ObjDetail",
        "$id" : ObjectId("5270c7b11f6a02100a000001")
    },
    "foo" : bar
}

实际上,使用Node.js和mongodb模块,我执行以下操作:

Actually, using Node.js and mongodb module, I do the following :

db.collection("Obj").findOne({"_id" : new ObjectID("5962c7b53b6a02100a000085"},
function(err, item) {
    db.collection(item.$ref).findOne({"_id" : item.$id}, function(err,subItem){
        ...
    });
});

其实我制作2个查询,并获得2个对象。这是一种延迟加载(不完全但几乎都是)

In fact I make 2 queries, and get 2 objects. It's a kind of "lazy loading" (not exactly but almost)

我的问题很简单:是吗可以在一个查询中检索整个对象图吗?

My question is simple : is it possible to retrieve the whole object graph in one query ?

谢谢

推荐答案

由于从MongoDB Nodejs API中删除了db.dereference方法,因此Vladimir的答案仍然无效:

Answer of Vladimir is not still valid as the db.dereference method was deleted from MongoDB Nodejs API:

https://www.mongodb.com/blog/post/introducing-nodejs-mongodb-20-driver


简化了db实例对象。我们删除了以下方法:

The db instance object has been simplified. We've removed the following methods:

db.dereference由于服务器中不推荐使用db引用

db.dereference due to db references being deprecated in the server

这篇关于Nodejs + mongodb:如何查询$ ref字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆