我希望能够将喜欢的ID添加到报告中。
这是我喜欢的路线,类似/添加是有问题的路线:
const express = require('express')
const likeRoutes = express.Router()
let Like = require('../models/Like')
let Report = require('../models/Report')
likeRoutes.route('/').get(function(req, res) {
Like.find(function(err, like) {
if (err) {
console.log(err)
} else {
res.json(like)
}
})
})
likeRoutes.route('/:id').get(async (req, res) => {
console.log(req.params.id)
let id = req.params.id
Like.findById(id, function(err, like){
res.json(like)
})
})
likeRoutes.route('/add').post(function(req, res){
let like = new Like({
value: req.body.value,
_report: req.body._report
})
like.save((err, doc) => {
if (err)
res.send(err)
console.log(req.body._report)
Report.findOneAndUpdate(req.body._report,
{ $push: { like: doc._id} },
{ new: true , useFindAndModify: false},
(err, post) => {
if (err)
res.send(err)
res.json({doc})
}
)
})
})
likeRoutes.route('/update/:id').post(function(req, res){
Like.findById(req.params.id, function(err, like) {
if (!like)
res.status(404).send('data is not found')
else
like.title = req.body.title
like.desc = req.body.desc
like.markdown = req.body.markdown
like.save().then(like => {
res.json('Like updated!!!')
})
.catch(err => {
res.status(400).send('Update didnt work')
})
})
})
module.exports = likeRoutes
这是我的报告模型:
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,
ref: 'Like'
},
player: {
type: mongoose.Schema.Types.ObjectId,
required: true,
ref: 'Player'
}
}, { timestamps: true })
module.exports = mongoose.model('Report', Report)
这是我喜欢的模特:
const mongoose = require('mongoose')
const Schema = mongoose.Schema
let Like = new Schema({
value: {
type: Number
},
_report: {
type: String,
ref: 'Report'
}
}, { timestamps: true })
module.exports = mongoose.model('Like', Like)
当我尝试在邮递员中添加一个赞时,就可以创建一个赞。
但是,当我去查看特定主题的报告时,没有类似主题。
我猜想这与我的模型或路线的配置有关。
当我console.log req.body._report时,通过正确的值。
答案 0 :(得分:0)
我不希望在报告架构中设置为数组。 $ push仅在您推入的模式是数组的情况下有效:https://docs.mongodb.com/manual/reference/operator/update/push/