Nodejs Mongoose简单的连表查询
Nodejs Mongoose简单的连表查询
原文摘自我的前端博客,欢迎大家来访问 http://www.hacke2.cn
像我这篇文章所说的基于Node.js + jade + Mongoose 模仿gokk.tv,当时停止开发是因为我深深的感觉到当时想错了,应该用两个Schema,而不是一个下面又有数组来存,这样取数据是方便,当时分页相当麻烦,不能使用原生提供的limit方法。 今天看到一本书上有讲,尝试了一把,记录下来 我们实验的场景为一个班级有N多学生,先通过学生ID找到班级名称(是不是被玩腻了?) 先来将Schema定义好
ClazzSchema :
var mongoose = require('mongoose')
var ClazzSchema = new mongoose.Schema({
clazzName:String
})
//其他方法省略…
}
module.exports = ClazzSchema
StudentSchema :
var mongoose = require(‘mongoose’)
var StudentSchema = new mongoose.Schema({
name:String,
clazzID : {
type : mongoose.Schema.ObjectId,
ref : ‘Clazz’
}
})
StudentSchema.statics = {
findClazzNameByStudentId:function(studentId, callback){
return this
.findOne({_id : studentId}).populate(‘clazzID’)
.exec(callback)
}
//其他方法省略…
}
module.exports = StudentSchema
可以看到,主需要将ClazzID设为ref到Clazz,依赖为你建立Model时的名称就可以了,要查询Clzz使用populate 下面是Model
var mongoose = require('mongoose')
var ClazzSchema = require('../schemas/clazzSchema')
var Clazz = mongoose.model('Clazz',ClazzSchema)
module.exports = Clazz
var mongoose = require('mongoose')
var StudentSchema = require('../schemas/studentSchema')
var Student = mongoose.model('Student',StudentSchema)
module.exports = Student
大同小异,着重看test.js
var mongoose = require('mongoose')
var Clazz = require('./models/clazzModel')
var Student = require('./models/studentModel')
//var db = mongoose.createConnection('localhost', 'gokk')
mongoose.connect('mongodb://localhost/test')
/*var clazz = new Clazz(
{
clazzName:'软件2班'
}
);
clazz.save(function (argument){
console.log('true');
});*/
/*var student = new Student({
name : 'hacke2',
clazzID : '542b5fcc49df6e741d8d15f5'
})
student.save(function (err){
console.log('true');
})*/
Student.findClazzNameByStudentId('542b600a683d59a80d4ee632', function (err, student){
if(err) console.log(err);
console.log(student.clazzID.clazzName);
})
之前添加了两班级:软件一班和软件二班
我们在新增hacke2时将classID设为软件2班的,查新hacke2时自动就会把关键的 Class查询到
{ _id: 542b600a683d59a80d4ee632,
name: 'hacke2',
clazzID: { _id: 542b5fcc49df6e741d8d15f5, clazzName: '软件2班', __v: 0 },
__v: 0 } [](http://www.hacke2.cn/gokk/)
Nodejs Mongoose简单的连表查询
原文摘自我的前端博客,欢迎大家来访问
http://www.hacke2.cn
在实际项目中,我们经常需要进行复杂的数据库查询操作。本文将介绍如何使用Mongoose进行简单的连表查询。我们将以一个班级和学生的关系为例,演示如何通过学生的ID找到对应的班级名称。
Schema定义
首先,我们需要定义两个Schema,一个是班级Schema,另一个是学生Schema。学生Schema中包含一个clazzID
字段,该字段引用了班级Schema。
// ClazzSchema.js
var mongoose = require('mongoose');
var ClazzSchema = new mongoose.Schema({
clazzName: String
});
module.exports = ClazzSchema;
// StudentSchema.js
var mongoose = require('mongoose');
var StudentSchema = new mongoose.Schema({
name: String,
clazzID: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Clazz'
}
});
StudentSchema.statics = {
findClazzNameByStudentId: function(studentId, callback) {
return this
.findOne({ _id: studentId })
.populate('clazzID')
.exec(callback);
}
};
module.exports = StudentSchema;
Model定义
接下来,我们需要创建Model来操作这些Schema。
// ClazzModel.js
var mongoose = require('mongoose');
var ClazzSchema = require('../schemas/clazzSchema');
var Clazz = mongoose.model('Clazz', ClazzSchema);
module.exports = Clazz;
// StudentModel.js
var mongoose = require('mongoose');
var StudentSchema = require('../schemas/studentSchema');
var Student = mongoose.model('Student', StudentSchema);
module.exports = Student;
测试代码
最后,我们编写测试代码来验证我们的实现是否正确。
// test.js
var mongoose = require('mongoose');
var Clazz = require('./models/clazzModel');
var Student = require('./models/studentModel');
mongoose.connect('mongodb://localhost/test', { useNewUrlParser: true, useUnifiedTopology: true });
// 添加测试数据
/*
var clazz = new Clazz({
clazzName: '软件2班'
});
clazz.save(function (err) {
if (err) console.log(err);
else console.log('Class saved');
});
*/
/*
var student = new Student({
name: 'hacke2',
clazzID: '542b5fcc49df6e741d8d15f5'
});
student.save(function (err) {
if (err) console.log(err);
else console.log('Student saved');
});
*/
// 查询学生并获取班级名称
Student.findClazzNameByStudentId('542b600a683d59a80d4ee632', function (err, student) {
if (err) console.log(err);
else console.log(student.clazzID.clazzName); // 输出 "软件2班"
});
解释
-
Schema定义:
ClazzSchema
定义了一个班级模型,包含一个字符串类型的clazzName
字段。StudentSchema
定义了一个学生模型,包含一个字符串类型的name
字段和一个引用Clazz
模型的clazzID
字段。
-
静态方法:
- 在
StudentSchema
中定义了一个静态方法findClazzNameByStudentId
,用于根据学生ID查找学生,并通过.populate('clazzID')
方法填充clazzID
字段。
- 在
-
Model定义:
- 创建了
Clazz
和Student
两个Model,分别对应ClazzSchema
和StudentSchema
。
- 创建了
-
测试代码:
- 使用
mongoose.connect
连接到MongoDB数据库。 - 通过
Student.findClazzNameByStudentId
方法查询学生信息,并输出对应的班级名称。
- 使用
通过这种方式,我们可以轻松地进行连表查询,而不需要手动处理复杂的JOIN操作。
代码格式化一下嘛
重庆即视感
在这个例子中,我们有两个模型 Clazz
和 Student
,其中 Student
模型中的 clazzID
字段引用了 Clazz
模型。为了实现通过学生的ID查询其所在的班级名称,我们使用了 Mongoose 的 populate
方法。
Schema 定义
// ClazzSchema.js
var mongoose = require('mongoose');
var ClazzSchema = new mongoose.Schema({
clazzName: String
});
module.exports = mongoose.model('Clazz', ClazzSchema);
// StudentSchema.js
var mongoose = require('mongoose');
var StudentSchema = new mongoose.Schema({
name: String,
clazzID: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Clazz'
}
});
StudentSchema.statics = {
findClazzNameByStudentId: function(studentId, callback) {
return this
.findOne({ _id: studentId })
.populate('clazzID')
.exec(callback);
}
};
module.exports = mongoose.model('Student', StudentSchema);
Model 导出
// clazzModel.js
var mongoose = require('mongoose');
var ClazzSchema = require('../schemas/clazzSchema');
var Clazz = mongoose.model('Clazz', ClazzSchema);
module.exports = Clazz;
// studentModel.js
var mongoose = require('mongoose');
var StudentSchema = require('../schemas/studentSchema');
var Student = mongoose.model('Student', StudentSchema);
module.exports = Student;
测试代码
// test.js
var mongoose = require('mongoose');
var Clazz = require('./models/clazzModel');
var Student = require('./models/studentModel');
mongoose.connect('mongodb://localhost/test');
Student.findClazzNameByStudentId('542b600a683d59a80d4ee632', function(err, student) {
if (err) console.log(err);
console.log(student.clazzID.clazzName);
});
解释
-
Schema 定义:
ClazzSchema
定义了一个班级模型,包含班级名称字段。StudentSchema
定义了一个学生模型,包含姓名字段和一个引用Clazz
模型的clazzID
字段。
-
静态方法:
- 在
StudentSchema
中定义了一个静态方法findClazzNameByStudentId
,用于通过学生ID查询并填充班级信息。
- 在
-
Model 导出:
- 将
ClazzSchema
和StudentSchema
导出为对应的模型。
- 将
-
测试代码:
- 使用
mongoose.connect
连接数据库。 - 调用
Student.findClazzNameByStudentId
方法,通过学生ID查询并打印班级名称。
- 使用
这样就可以通过学生ID查询到相应的班级名称了。