如何使用外键进入另一个集合

问题描述 投票:0回答:1

我有这些收藏(

books
book_genres
genres
books
) 我的
book
Schema
就是这样

var bookModel = function () {
    var bookSchema = mongoose.Schema({
        _id: mongoose.Schema.Types.ObjectId,
        author_id: {
            type: mongoose.Schema.Types.ObjectId,
            ref: "Author",
        },
        title: String,
        description: String,
        cover: String,
        likes: Number,
    });
    return mongoose.model("Book", bookSchema);
};

module.exports = new bookModel();

我正在使用

dust
模板,并且我正在像这样在我的布局上渲染该集合数据

    {#books}
             <div class="large-4 small-12 columns book">
                <div class="row img-row">
                <img src="{.cover}" alt="">
                </div>
                <div class="row">
                <h3 class="small-12">{.title}</h3>
                  <h4 class="small-5 columns ">{.author_id}</h4>
                   <h4 class="small-7 columns ">{.name}</h4>
                </div>
               
                   <div class="row p-row">
                    <p class="small-12">{.description}</p>
                   </div>
             </div>

     {/books}

我的

author
Schema
就是这样

var authorModel = function () {
    var authorSchema = mongoose.Schema({
        _id: mongoose.Schema.Types.ObjectId,
        name: String,
    });
    return mongoose.model("Author", authorSchema);
};

我希望能够到达

author
name
,这样我就可以通过从
author_id
book
获得的
Schema
将其渲染到我的布局上(当然,作者集合与
id
集合中的
author_id
相同)
我尝试寻找一些解决方案,但没有人使用

books

模板,所以我无法弄清楚

    

node.js mongodb mongoose dust.js
1个回答
1
投票

dust

来解决
populate参考:
Author

然后您应该能够通过以下方式访问引用的用户字段:

bookModel.find({}).populate('author_id').exec();

在您的情况下,您应该将代码更改为:

<h4 class="small-7 columns ">{.author_id.name}</h4>

© www.soinside.com 2019 - 2024. All rights reserved.