关联查询:populate | lean
-
数据库得提供关联数据(新增clazzs集合,并且将students中引入该外键)
-
服务器:创建该新集合的模型
// ./dao/clazzsModel.js const mongoose = require("mongoose"); //下面是生产model的代码:(借助于schema) const clazzsSchema = mongoose.Schema({ name: String, },{versionKey:false}); const clazzsModel = mongoose.model('clazzs', clazzsSchema); module.exports = clazzsModel;
-
学生模型建立了联系:
const mongoose = require("mongoose"); require("./clazzsModel");//依赖clazzsModel const studentsSchema = mongoose.Schema({ name: String, age: Number, gender: {type:String}, className: {type:mongoose.Schema.Types.ObjectId,ref:"clazzs"},//联系的建立 headPic:String, zz:[String] },{versionKey:false}); const studentsModel = mongoose.model('students', studentsSchema); module.exports = studentsModel;
-
使用关联查询:
const students = await studentsModel .find(condition ? condition : {}) .populate("className",["_id","name"])//这里使用,其中参数代表了哪一个字段是外键,数组中的字段名是需要关联过来的字段 .skip((page - 1) * limit) .limit(limit);
-
页面关于class的地方进行修改。
- info页面显示的地方
- update页面选择班级的地方(ajax渲染)
- add页面选择班级的地方(ajax渲染)
;
module.exports = studentsModel;
4. 使用关联查询:
```js
const students = await studentsModel
.find(condition ? condition : {})
.populate("className",["_id","name"])//这里使用,其中参数代表了哪一个字段是外键,数组中的字段名是需要关联过来的字段
.skip((page - 1) * limit)
.limit(limit);
-
页面关于class的地方进行修改。
- info页面显示的地方
- update页面选择班级的地方(ajax渲染)
- add页面选择班级的地方(ajax渲染)