[英]Populate in mongoose not working as expected
This is the model for course and topic, I want to populate topic in course with the help of mongoose.这是课程和主题的 model,我想在 mongoose 的帮助下填充课程中的主题。 When we call API I want a joint result of course and topic.
当我们调用 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 };
This is API for GET, and I use populate as well but not able to get the joint result of course and topic.这是 GET 的 API,我也使用填充,但无法获得课程和主题的联合结果。
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)
}
})
})
I want output like this:我想要这样的 output :
{
"_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
}
Whay did you do that?你为什么那样做?
router.route('/').get((req, res) => {
Course.find().populate('topic').exec((error, data) => {
if (error) {
return next(error)
} else {
res.json(data)
}
})
})
and not this instead?而不是这个?
router.get('/',(req, res) => {
Course.find().populate('topic').exec((error, data) => {
if (error) {
return next(error)
} else {
res.json(data)
}
})
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.