Mongoose填充嵌入式 [英] Mongoose populate embedded

查看:186
本文介绍了Mongoose填充嵌入式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Mongoose.js并且无法解决3级层次结构文档的问题。

I use Mongoose.js and cannot solve problem with 3 level hierarchy document.

有2种方法可以做到。

首先 - 没有参考。

C = new Schema({
    'title': String,
});

B = new Schema({
    'title': String,
    'c': [C]
});

A = new Schema({
    'title': String,
    'b': [B]
});

我需要显示C记录。我怎么能填充/找到它,只知道C的_id?

I need to show C record. How can i populate / find it, knowing only _id of C?

我尝试使用:

A.findOne({'b.c._id': req.params.c_id}, function(err, a){
    console.log(a);
});

但我不知道如何从者返回一个只需要对象的对象。

But i dont know how to get from returnet a object only c object that i need.

第二如果使用refs:

C = new Schema({
    'title': String,
});

B = new Schema({
    'title': String,
    'c': [{ type: Schema.Types.ObjectId, ref: 'C' }]
});

A = new Schema({
    'title': String,
    'b': [{ type: Schema.Types.ObjectId, ref: 'B' }]
});

如何填充所有B,C记录以获得层次结构?

How to populate all B, C records to get hierarchy?

我尝试使用这样的东西:

I was try to use something like this:

A
.find({})
.populate('b')
.populate('b.c')
.exec(function(err, a){
    a.forEach(function(single_a){
        console.log('- ' + single_a.title);
        single_a.b.forEach(function(single_b){
            console.log('-- ' + single_b.title);
            single_b.c.forEach(function(single_c){
                console.log('--- ' + single_c.title);
            });
        });
    });
});

但是它将为single_c.title返回undefined。我有办法填充吗?

But it will return undefined for single_c.title. I there way to populate it?

谢谢。

推荐答案

In Mongoose 4您可以在多个级别填充文档:

In Mongoose 4 you can populate documents across multiple levels:

假设您有一个用户架构,可以跟踪用户的朋友。

Say you have a User schema which keeps track of the user's friends.

var userSchema = new Schema({
  name: String,
  friends: [{ type: ObjectId, ref: 'User' }]
});

首先 populate()让你得到一个用户朋友列表。但是,如果您还想要用户的朋友朋友呢?在这种情况下,您可以指定填充选项,告诉mongoose填充所有用户朋友的 friends 数组:

Firstly populate() lets you get a list of user friends. But what if you also wanted a user's friends of friends? In that case, you can specify a populate option to tell mongoose to populate the friends array of all the user's friends:

User.
  findOne({ name: 'Val' }).
  populate({
    path: 'friends',
    // Get friends of friends - populate the 'friends' array for every friend
    populate: { path: 'friends' }
  });

取自: http://mongoosejs.com/docs/populate.html#deep-populate

这篇关于Mongoose填充嵌入式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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