我是mongodb和nodejs的新手,我想知道如何通过加入mongodb和nodejs中的集合来获取数据,我已经应用了populate方法,但对我不起作用。 我有一组课程,一个用于课程,一个用于主题,现在我想获取包含其课程和课程的课程,我想要一个主题,所以我如何获得这种类型的api结构。 这是课程模式:
const mongoose = require('mongoose');
var autoIncrement = require('mongoose-auto-increment');
const courseSchema = new mongoose.Schema({
_id:{type:Number,requre:true},
courseName:{
type:String,
},
classes: [
{
type: mongoose.Schema.Types.ObjectId,
ref: 'classes' }
]
},{ versionKey: false });
autoIncrement.initialize(mongoose.connection);
courseSchema.plugin(autoIncrement.plugin, 'Counter_course');
module.exports = mongoose.model('course',courseSchema,'courses')
这是类架构:
const mongoose = require('mongoose');
var autoIncrement = require('mongoose-auto-increment');
const classSchema = new mongoose.Schema({
className:{
type:String,requre:true
},
courseId: {
type: mongoose.Schema.Types.ObjectId,
ref: 'course'
}
},{ versionKey: false });
autoIncrement.initialize(mongoose.connection);
classSchema.plugin(autoIncrement.plugin, 'Counter_class');
module.exports = mongoose.model('classes',classSchema,'classes')
这是路线:
router.post('/coursesdetails',async(req,res)=>{
try{
const a2 = await allcourses.find()
.populate('classes')
.exec();
res.json(a2);
}
catch(err){
res.send('Error'+err)
}
});