【Mongoose】populate基本使用

在使用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);
                    }

        })
  • 2
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
Mongoose's `populate()` function is used to populate referenced fields in a document with actual data from another collection. It allows you to perform database joins in MongoDB. Let's say you have two models: `User` and `Post`. The `Post` model has a reference to the `User` model through a field called `author`. To use `populate()`, you would first define your models using Mongoose: ```javascript const mongoose = require('mongoose'); const userSchema = new mongoose.Schema({ name: String, age: Number, }); const postSchema = new mongoose.Schema({ title: String, content: String, author: { type: mongoose.Schema.Types.ObjectId, ref: 'User', }, }); const User = mongoose.model('User', userSchema); const Post = mongoose.model('Post', postSchema); ``` Now, let's say you want to find all posts and populate the `author` field with the actual user data. You can do that using the `populate()` function: ```javascript Post.find().populate('author').exec((err, posts) => { if (err) { console.error(err); return; } console.log(posts); }); ``` This will fetch all posts and populate the `author` field with the corresponding user data from the `User` collection. You can then access the populated data using dot notation, like `post.author.name`. You can also populate multiple fields by passing an array of field names to the `populate()` function, like `populate(['author', 'category'])`. It's important to note that populate is an expensive operation, as it involves multiple database queries. So, use it judiciously and consider using it only when necessary to avoid performance issues.

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值