【Mongoose】populate基本使用

本文介绍在Node.js开发中使用Mongoose的populate方法进行外键关联查询的方法。详细讲解了如何在Schema定义中设置关联字段,并提供了populate方法的具体使用示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在使用mongoose进行nodejs开发时,有很多场景都需要通过外键与另一张表建立关联,populate可以很方便的实现,因此总结一下populate的用法。

参考文档

https://segmentfault.com/a/1190000002727265

使用方法

首先,在建立模型时(schema),需要指定关联字段:

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

var UserSchema = new Schema({
    name  : { type: String, unique: true },
});
var CommentSchema = new Schema({
    commenter : { type: Schema.Types.ObjectId, ref: 'User' },
    content   : String
});

仔细观察上述代码,有一个陌生字段“ref”,在这里ref表示commenter通过ObjectId字段关联了User

:被关联的model的 type 必须是 ObjectId, Number, String, 和 Buffer 才有效)。

那么如何使用populate方法来跨表查询呢?

语法

**`Query.populate(path, [select], [model], [match], [options])`**

1.path

指定要查询的表

2.select(可选)

指定要查询的字段

3.model(可选)

类型:Model,可选,指定关联字段的 model,如果没有指定就会使用Schema的ref。

4.match(可选)

类型:Object,可选,指定附加的查询条件。

5.options(可选)

类型:Object,可选,指定附加的其他查询选项,如排序以及条数限制等等。

Catetory.find({_id:catId})
        .populate({path:'movies',select:'title poster',options:{limit:5}})
        .exec(function(err,catetories){
                    if (err) {
                        console.log(err);
                    }

        })
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值