javascript - 如何在不引用文档本身的情况下使用 mongoose 有条件地更新一个 DB 文档?
问题描述
例如我有
1 //for instance I have
2
3 app.post('/update', validate, async (req, res) => {
4 const {title, description, post_id} = req.body;
5
6 // I need to update one of them if they exist
7
8 if ((post_id && description) || title) {
9 // Need to update ether title or description or both without
10 try {
11 const postBack = await Post.find({_id: post_id, user_id: req.user.id});
12
13 const updated = await Post.updateOne(
14 {_id: post_id, user_id: req.user.id},
15 {
16 title: title ? title : postBack[0].title,
17 description: description ? description : postBack[0].description,
18 },
19 );
20
21 res.send('Success');
22
23 //How I can do the same but without Post.find()?
24 } catch (err) {
25 res.send(err);
26 }
27 } else {
28 res.send('Error');
29 }
30 });
~
我怎么能做同样的事情但没有 Post.find()?
不看这个>>> 有可恶的dashwoods怀疑诚意但现在他的优势。评论很容易阁楼也不不行。文雅的那些夫人享受着害羞的胖子快活。你最大的关节看起来很可怕。他私下可想而知。肥沃的心爱的人通过没有服务的老人是显而易见的。如果每次都不这样,就在那里盲目。自己忽略了你喜欢的方式,真诚地传递了他的企图。对消息山寨窗户做除了反对不文明。
解决方案
为您的更新创建一个对象,并且仅在您有新数据要设置时才更新该对象。
例如
const updateObj = {};
if (title) {
updateObj.title = title;
}
if (description) {
updateObj.description = description;
}
if (Object.keys(updateObj).length > 0 {
const updated = await Post.updateOne({_id: post_id, user_id: req.user.id}, updateObj);
}
推荐阅读
- nearprotocol - 无符号整数的 NEAR 和安全数学
- jenkins - 如何使用 AWS Parameter Store Build Wrapper Jenkins 插件
- flutter - Flutter 一起使用 navigator 和 ChangeNotifierProvider 的最佳方法是什么
- php - 无法使用实时模型 srmklive-paypal
- python - 为什么我使用 pip 下载 Python 包时会得到这么多的轮子文件
- javascript - 如何将值从子数组传递给父数组
- perl - 无法读取包含 % 符号的输入文件内容
- vuejs2 - 什么是 Vue 等价于 Angular 的“::”一次性绑定?
- javascript - 如何在knockoutJs和php中使用拖放?
- python - 使用两个键在 A 中而不是 B 中创建字典列表