首页 > 解决方案 > 如何在不引用文档本身的情况下使用 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怀疑诚意但现在他的优势。评论很容易阁楼也不不行。文雅的那些夫人享受着害羞的胖子快活。你最大的关节看起来很可怕。他私下可想而知。肥沃的心爱的人通过没有服务的老人是显而易见的。如果每次都不这样,就在那里盲目。自己忽略了你喜欢的方式,真诚地传递了他的企图。对消息山寨窗户做除了反对不文明。

标签: javascriptnode.jsmongodbmongoose

解决方案


为您的更新创建一个对象,并且仅在您有新数据要设置时才更新该对象。

例如

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);
}

推荐阅读