这是课程和主题的模型,我想在猫鼬的帮助下在课程中填充主题。当我们调用 API 时,我想要的是课程和主题的联合结果。
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
let courseSchema = new Schema({
course_id: {
type: Number
},
course_title: {
type: String
},
course_description: {
type: String
},
course_duration:{
type: Number
},
topic:{
type: mongoose.Schema.Types.ObjectId,
ref: "Topic"
}
}, {
collection: "courses"
})
let topicSchema = new Schema({
topic_id: {
type: Number
},
topic_title: {
type: String
},
topic_description: {
type: String
}
}
,{
collection: "topics"
})
const Topic = mongoose.model("Topic", topicSchema)
const Course = mongoose.model('Course', courseSchema)
module.exports = { Topic, Course };
这是GET的API,我也用populate但是不能得到课程和主题的联合结果。
let mongoose = require('mongoose'),
express = require('express'),
router = express.Router();
var { Topic, Course }= require('../models/Course')
router.route('/').get((req, res) => {
Course.find().populate('topic').exec((error, data) => {
if (error) {
return next(error)
} else {
res.json(data)
}
})
})
我想要这样的输出:
{
"_id": "5fea9d7cd6651122e04ce5ed",
"course_id": 2,
"course_title": "GOlang",
"course_description": "google ",
"course_duration": 11,
"topic_id": 3,
"topic_title": "hoisting",
"topic_description": "variable and function",
"__v": 0
}
答案 0 :(得分:0)
你为什么这样做?
router.route('/').get((req, res) => {
Course.find().populate('topic').exec((error, data) => {
if (error) {
return next(error)
} else {
res.json(data)
}
})
})
而不是这个吗?
router.get('/',(req, res) => {
Course.find().populate('topic').exec((error, data) => {
if (error) {
return next(error)
} else {
res.json(data)
}
})
})