我有这个api路由功能,需要更新主题记录以包括帖子的引用,然后保存正在创建的实际帖子记录。有没有更好的方法来做我想做的事?有可能吗?
const express = require('express');
const router = express.Router();
router.post('/:id/posts', (req,res) => {
const newPost = new Post({
post: req.body.post,
description: req.body.description,
topic_id: req.params.id
});
Topic.findById(req.params.id)
.then(topic => {
topic.posts.push(newPost._id);
})
.catch(err => {
res.send(err);
});
//how do i save this topic record I find and push an id into.
newPost.save().then(post => res.json(post));
});
github第33行:https://github.com/wolffles/bloccit-node/blob/express/routes/api/topics.js
答案 0 :(得分:1)
问题
如何保存找到和修改的主题记录?
答案
使用最新的JS async await语法尝试一下。
router.post('/:id/posts', async (req,res) => {
const newPost = new Post({
post: req.body.post,
description: req.body.description,
topic_id: req.params.id
});
try {
await Topic.findById(req.params.id, (err, doc) => {
doc.posts.push(newPost._id);
doc.save();
});
const post = await newPost.save()
res.json(post)
} catch(err) {
res.send(err)
}
});
让我知道这是否对您有用。
答案 1 :(得分:-1)
只需将文档保存在主题返回的成功承诺中即可。就像我在下面写道。 让我知道是否行得通。
const express = require('express');
const router = express.Router();
router.post('/:id/posts', (req,res) => {
const newPost = new Post({
post: req.body.post,
description: req.body.description,
topic_id: req.params.id
});
Topic.findById(req.params.id)
.then(topic => {
topic.posts.push(newPost._id);
//now update the newPost
newPost.topicObj = topic;
newPost.save().then(post => res.json(post));
})
.catch(err => {
res.send(err);
});
//how do i save this topic record I find and push an id into.
});