【Mongoose】populate基本使用

来源:互联网 发布:直男癌语录知乎 编辑:程序博客网 时间:2024/06/05 09:36

在使用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);                    }        })
原创粉丝点击