gpt4 book ai didi

node.js - 在另一个集合中保存新文档后,是否可以在回调函数中更新文档?

转载 作者:太空宇宙 更新时间:2023-11-03 23:56:18 25 4
gpt4 key购买 nike

我正在将 newPost 文档保存到 posts 集合中,并且在 then() 函数中,我想更新其他文档,但在标签集合中。但是,由于某种原因,标签集合中的这种更改不会发生,并且 res.json(post) 不会按应有的方式返回新帖子。

我正在使用 postman 向服务器发出请求。

当我取出对标签集合进行更改的代码片段时,res.json(post) 起作用,并且创建的帖子在 Postman 中以 json 格式返回,但是,当放回去时,似乎没有任何效果。然而,该帖子被推送到数据库,并且可以在集合中查看。

const newPost = new Post({
authorId: user._id,
text: req.body.text,
title: req.body.title,
tags: req.body.tags.split(", ")
});

newPost.save()
.then(post => {
// here, I'd like to do the following commented section or something
//similar:
// Tag.findAndModify({
// query: {name: {$all: [post.tags]}},
// update: {
// $push: {posts: post._id},
// $set: {lastActive: new Date()}
// }
// });
res.json({post});
}).catch(err=>res.json(err));

没有注释的部分,帖子已成功添加到数据库,res.json(post)在Postman中返回帖子;取消注释该部分,post成功添加到数据库,但没有发生标签集合修改,postman中res.json(post)为空

最佳答案

保存后需要返回 res.json,因为它是异步操作。

    const newPost = new Post({
authorId: user._id,
text: req.body.text,
title: req.body.title,
tags: req.body.tags.split(", ")
});

newPost.save()
.then(post => {
// here, I'd like to do the following commented section or something
//similar:
Tag.findAndModify({
query: {name: {$all: [post.tags]}},
update: {
$push: {posts: post._id},
$set: {lastActive: new Date()}
}
}).exec((err,tags)=>{
if(err) //return error
res.json({post,tags});
});

}).catch(err=>res.json(err));

关于node.js - 在另一个集合中保存新文档后,是否可以在回调函数中更新文档?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56945306/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com