用JSON渲染猫鼬关系

时间:2019-05-17 03:14:49

标签: node.js mongodb express mongoose

我有两个模型。

赞:

const mongoose = require('mongoose')
const Schema = mongoose.Schema

let Like = new Schema({
    value: {
        type: Number
    }
}, { timestamps: true })

module.exports = mongoose.model('Like', Like)

AND

报告:

const mongoose = require('mongoose')
const Schema = mongoose.Schema

let Report = new Schema({
    title: {
        type: String
    },
    summary: {
        type: String
    },
    analysis: {
        type: String
    },
    source_title: {
        type: String
    },
    source_link: {
        type: String
    },
    author: {
        type: String
    },
    like: {
        type: mongoose.Schema.Types.ObjectId,
        required: true,
        ref: 'Like'
    },
    player: {
        type: mongoose.Schema.Types.ObjectId,
        required: true,
        ref: 'Player'
    }
}, { timestamps: true })

module.exports = mongoose.model('Report', Report)

我有两个目标:

  1. 我希望能够跟踪每一个喜欢的人并将其与报告相关联。
  2. 我希望能够在此路由中将报告呈现为json。
const express = require('express')
const reportRoutes = express.Router()
let Report = require('../models/Report')


reportRoutes.get('/', async (req, res) => {

    try {

       const report = await Report.find()
        .populate({path: 'like'})
        .populate({
             path    : 'player',
             populate: [
                 { path: 'team' }
             ]
        })

        res.json(report)

    } catch (e) {
        res.status(500).send()
    }
})

reportRoutes.route('/:id').get(async (req, res) => {
    let id = req.params.id
    Report.findById(id, function(err, report){
        res.json(report)
    })
})

reportRoutes.route('/add').post(function(req, res){
    let report = new Report(req.body)
    report.save()
        .then(report => {
            res.status(200).json({'report': 'report added successfully!'})
        })
        .catch(err => {
            res.status(400).send('adding new report failed :(')
        })
})

reportRoutes.route('/update/:id').post(function(req, res){
    Report.findById(req.params.id, function(err, report) {
        if (!report)
            res.status(404).send('data is not found')
        else
            report.title = req.body.title
            report.desc = req.body.desc
            report.markdown = req.body.markdown

            report.save().then(report => {
                res.json('Report updated!!!')
            })
            .catch(err => {
                res.status(400).send('Update didnt work')
            })
    })
})

module.exports = reportRoutes

当前配置的方式有效,但是,我觉得有一定的局限性。

每次我为报告创建一个赞时,我还必须更新报告以添加特定赞的ID。

我猜想有更好的方法来做到这一点。我的背景是Rails和Posgresql,所以Mongo / Mongoose让我有些失望。

0 个答案:

没有答案