簡體   English   中英

填充 mongoose 未按預期工作

[英]Populate in mongoose not working as expected

這是課程和主題的 model,我想在 mongoose 的幫助下填充課程中的主題。 當我們調用 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)
        }
      })
    })

我想要這樣的 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
    }

你為什么那樣做?

   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)
    }
  })
})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM