当前位置:Gxlcms > JavaScript > mongoose中利用populate处理嵌套的方法

mongoose中利用populate处理嵌套的方法

时间:2021-07-01 10:21:17 帮助过:7人阅读

前言

nodejs在使用mongdb数据库中经常会使用到嵌套,比如一个多级分类等。这里我使用学校-->学院-->学生来展示使用populate处理嵌套。

定义modal

在模式中,我们需要使用Schema.ObjectId来表示要指向数据在mongodb数据库中的_id。

学校

在学校的Schema中,colleges属性是要包含的学院的_id属性数组。

  1. var SchoolSchema = new Schema({
  2. name: String,
  3. colleges: [{
  4. type: Schema.ObjectId,
  5. ref: 'College'
  6. }],
  7. createTime: {
  8. type: Date,
  9. default: Date.now()
  10. }
  11. });
  12. var School = mongoose.model('School', SchoolSchema);

学院

  1. var CollegeSchema = new Schema({
  2. name: String,
  3. students: [{
  4. type: Schema.ObjectId,
  5. ref: 'Student'
  6. }],
  7. createTime: {
  8. type: Date,
  9. default: Date.now()
  10. }
  11. });
  12. var College = mongoose.model('College', CollegeSchema);

学生

  1. var StudentSchema = new Schema({
  2. name: String,
  3. sex: String,
  4. age: Number,
  5. createTime: {
  6. type: Date,
  7. default: Date.now()
  8. }
  9. });
  10. var Student = mongoose.model('Student', StudentSchema);

查找

直接查找

查找学校并找到指向的学院

  1. School
  2. .find()
  3. .populate('colleges', ['_id','name'])
  4. .exec((err, schools) => {
  5. if (err) {
  6. console.log(err)
  7. }
  8. console.log(schools)
  9. })

populate的第一个参数是学校表中需要指向学院表的属性,即colleges;第二个参数为要在学院中查找的属性。如果不填写第二个参数,则默认全都查出。

这样查找出的结果中,学院的学生属性是该学院包含的学生的_id属性。如果需要都查找出来需要使用嵌套populate。

嵌套

  1. School
  2. .find()
  3. .populate({
  4. path: 'colleges',
  5. select: ['_id', 'name'],
  6. // model: 'College',
  7. populate: {
  8. path: 'students',
  9. select: ['_id', 'name']
  10. // model: 'Student'
  11. }
  12. })
  13. .sort({
  14. createTime: -1
  15. }).exec(function(err, schools) {
  16. if (err) {
  17. console.log(err)
  18. }
  19. });

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对脚本之家的支持。

人气教程排行