首页 > 解决方案 > 添加评论的问题

问题描述

我正在制作一个节点 API。我一直在为故事添加评论。

我可以创建评论,但不是将其推送到给定的故事,而是试图创建一个新的故事实例。

Story.findOne(req.params.id, (err, foundstory) => {
        if(err){
            res.status(500).json({msg:err})
        }else{
            let comment = new Comment()
            comment.body = req.body.body
            comment.author = req.body.author
            console.log(foundstory)

            //save comment//
            comment.save((err, comment) => {
                if(err){
                    res.status(500).json({msg:err})
                }else{
                    //pushing comment to comments array (ref) in story
                    foundstory.comments.push(comment)
                    foundstory.save()
                    res.status(200).json({msg:"Comment saved"})
                
                }
            })
        }
    })

故事架构

import mongoose from 'mongoose'
import User from './user'
import Comment from './comment'

const Schema = mongoose.Schema
const ObjectID = mongoose.Schema.Types.ObjectId 

const storySchema = new Schema({
    //subdoc ref from user 
    author: {type: ObjectID, ref: 'User'},
    //subdoc ref from comment
    comments: [{
        type: ObjectID,
        ref: 'Comment'
    }],
    //contents of story//
    title: {type: String, required: true},
    body: {type: String, required: true},
    date: {type: Date, default: Date.now()},
    tags: [{type: String}]
})

module.exports = mongoose.model('Story', storySchema)

评论模式

import mongoose from 'mongoose'
import User from './user'
const Schema = mongoose.Schema
const ObjectID = mongoose.Schema.Types.ObjectId

const commentSchema = new Schema({
    body : {type: String, required: true},
    author: {type: ObjectID, ref: 'User'}
})

module.exports = mongoose.model('Comment', commentSchema)

我的“故事”模式中有一个“评论”类型的数组。我的尝试是将这些评论推送到该数组。

标签: javascriptnode.jsexpressmongoose

解决方案


尝试像这样更改您的代码:

Story.findById(req.params.id, (err, foundstory) => {
    if (err) res.status(500).json({
        msg: err
    });
    else if (!foundStory) res.status(400).json({
        msg: "Story Not Found"
    });
    else {
        let comment = new Comment();
        comment.body = req.body.body;
        comment.author = req.body.author;

        //save comment//
        comment.save(async (err, comment) => {
            if (err) res.status(500).json({
                msg: err
            });
            else {
                foundstory.comments.push(comment._id);
                await foundstory.save();
                res.status(200).json({
                    msg: "Comment saved"
                })
            }
        })
    }
})

我已经用findById()改变了findOne()方法,也是 'foundstory. save() ' 方法是一个异步调用,所以我使用 async\await 来处理它。希望这可以帮助 :)


推荐阅读