node.js - 如何使用 mongoose refs 处理一对多关系
问题描述
我有两个模式,如下所示
学生.js
module.exports = (mongoose) => {
const Schema = mongoose.Schema;
const studentsSchema = new Schema({
name : {
type : String,
required : true
},
roll : {
type : Number,
default : null
},
class : {
type : String,
default : null
}
});
return mongoose.model('students', studentsSchema);
};
主题.js
module.exports = (mongoose) => {
const Schema = mongoose.Schema;
const subjectSchema = new Schema({
title : {
type : String,
required : true
},
author : {
type : String,
default : null
},
price : {
type : Number,
default : null
},
studentId : {
type : String
}
});
return mongoose.model('subjects', subjectSchema);
};
我需要在 Student 模型上运行 find 查询以获取一组学生。每个学生都将包含一系列他的科目。主题数组的每个索引都将包含主题的完整对象。如下所示。
[
{
name : "student 1",
roll : 1234,
class : "TEN",
subjects : [
{
title : 'English',
author : 'peter',
price : 210
},
{
title : 'Math',
author : 'Nelson',
price : 222
}
]
}
]
我怎样才能通过使用 refs 来实现它?
解决方案
您可以使用ref
功能和填充。
它看起来像:
const subjectSchema = new Schema({
title : {
type : String,
required : true
},
author : {
type : String,
default : null
},
price : {
type : Number,
default : null
}
// studentId : {
// type : String
// }
// ^ You don't need to save the student id, since the ids of the subject
// will be saved in your Student schema
});
mongoose.model('subjects', subjectSchema);
const studentsSchema = new Schema({
name : {
type : String,
required : true
},
roll : {
type : Number,
default : null
},
class : {
type : String,
default : null
},
subjects: [{ type: Schema.Types.ObjectId, ref: 'subjects' }]
// ^ Add the reference to subjects
});
mongoose.model('students', studentsSchema);
然后就可以查询了
mongoose.model( "students" ).find().populate( "subjects" ).exec( ( results, error ) => {
console.log( results ); // { ... subjects: [ ... ] }
} );
推荐阅读
- go - 如何在 Golang Gin 中显示自定义错误和中止
- react-native - 我如何开玩笑地测试我的组件的嵌套组件
- assembly - NASM 实模式寻址问题
- asp.net-core - 未调用 httppost 方法“显示 400 错误请求”
- python - 带有kwargs的函数的python类型签名(typing.Callable)
- java - 使用 JavaStreams 过滤复杂的列表元素 - 代码优化
- python - 在 python 环境中,如何从特定版本导入包?
- bindy - 从字段为枚举的 CSV 创建 POJO
- c# - 将视图和控制器放在与 ASP.NET Core Web 应用程序不同的项目中
- javascript - GoogleAppScript TABLE WEB,当它具有日期格式值时,我无法显示表值