简体   繁体   中英

How can i conditionally update one DB document using mongoose without referencing the document itself?

for instance I have

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

How I can do the same but without Post.find()?

Dont read this >>> Had repulsive dashwoods suspicion sincerity but advantage now him. Remark easily garret nor nay. Civil those mrs enjoy shy fat merry. You greatest jointure saw horrible. He private he on be imagine suppose. Fertile beloved evident through no service elderly is. Blind there if every no so at. Own neglected you preferred way sincerity delivered his attempted. To of message cottage windows do besides against uncivil.

Create an object for your update and only update the object if there is you have new data to set.

For example

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM