javascript - 添加评论的问题
问题描述
我正在制作一个节点 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)
我的“故事”模式中有一个“评论”类型的数组。我的尝试是将这些评论推送到该数组。
解决方案
尝试像这样更改您的代码:
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 来处理它。希望这可以帮助 :)
推荐阅读
- flutter - 在 Flutter Desktop 中将监视器输出发送到 LCD 投影仪
- angular - android上的Nativescript底部导航未按预期呈现
- vb.net - 在 vb.net 中调用包中的 Oracle 函数
- ansible - 添加特定行的文本结尾
- windows - 尝试在 Windows 上执行 c++ 时出现本机命令行错误(通过 MinGW 编译)
- python - 根据其他列值/ Pandas -Python 在数据框中创建 ID 列
- cloud-foundry - 禁用 Cloud Foundry 部署的应用程序的 iframe 嵌入
- android - 安卓重复apk
- controls - 如何调整 PID 输出限制器
- c++ - 如何在水平布局中对齐 QPushButton 和 QComboBox?