我有两个模型。
赞:
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)
我有两个目标:
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让我有些失望。