猫鼬填充嵌入 [英] Mongoose populate embedded

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

问题描述

我使用 Mongoose.js,无法解决 3 级层次文档的问题.

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

有两种方法可以做到.

第一 - 没有引用.

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.

第二(如果使用引用):

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?

谢谢.

推荐答案

在 Mongoose 4 中,您可以跨多个级别填充文档:

In Mongoose 4 you can populate documents across multiple levels:

假设您有一个 User 架构来跟踪用户的朋友.

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() 让你得到一个用户好友列表.但是如果你还想要一个用户的朋友的朋友怎么办?在这种情况下,您可以指定一个 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-填充

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

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