javascript - 填充猫鼬没有按预期工作
问题描述
这是课程和主题的模型,我想在猫鼬的帮助下填充课程中的主题。当我们调用 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,我也使用填充但无法获得课程和主题的联合结果。
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
}
解决方案
你为什么那样做?
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)
}
})
})
推荐阅读
- python - Kill Python thread running a web server
- kubernetes - 如何修复:数字海洋上 nginx-ingress 的空 IP 地址
- ffmpeg - 将原始数据复制到 MP4 的 ffmpeg 命令挂起并且永远不会完成
- javascript - Messenger Postback 按钮根本不起作用
- python-3.x - nn.NLLLoss() 目标大小问题
- django - 覆盖模型保存方法不允许赋值
- android - NativeScript 和 Angular 代码共享 + 延迟加载的模块路径
- java - MustacheException:第 15 行没有名称为“Id”的方法或字段。Whitelabel 错误页面
- java - jar 执行文件中缺少一些文本
- reactjs - Ant design - 如何在每次选择后自动关闭选择(“标签”或“多个”模式)下拉菜单?