最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - how to only update specific fields and leave others with the previous values in findandupdate with Mongoose - Stack

programmeradmin4浏览0评论

I've created an update function using Mongoose. However whenever I update the data using findOneAndUpdate. It updates only the fields entered and making it so that the others are now null or empty. I would like it so that when the user is updating and they dont update a filed it should remain as what it was before instead of being empty now. essentially only update the fields entered.

heres my routes

router.post("/updateStock", (req, res) => {
    const filter = {prodId: req.body.prodID}

    const update = req.body

    Product.findOneAndUpdate(filter, update, {new: true}).then((product) => {
        console.log("success");
        res.send(product);
  }).catch(err => {
       console.log("err", err);
       res.status(500).send(err);
  })

});

here's an example of req.body. I've only updated the title and catergory on the frotnend meaning everything else is blank. When it saves in the DB it ony updates the title and catergory and leaves everything else blank. I would like it to not insert the blank ones into the DB and leave the fields as they are

{
  prodId: 'iPhone 111001200',
  title: 'iPhone 11 Pro',
  manufacturer: '',
  catergory: 'Electronics',
  price: '',
  quantity: ''
}

Here's my model

const mongoose = require("mongoose");

const Product = mongoose.model(
  "Product",
  new mongoose.Schema({
    title: String,
    manufacturer: String,
    price: String,
    catergory: String,
    quantity: String,
    prodID: String, 
    images: Array
  })
);

module.exports = Product;

I've created an update function using Mongoose. However whenever I update the data using findOneAndUpdate. It updates only the fields entered and making it so that the others are now null or empty. I would like it so that when the user is updating and they dont update a filed it should remain as what it was before instead of being empty now. essentially only update the fields entered.

heres my routes

router.post("/updateStock", (req, res) => {
    const filter = {prodId: req.body.prodID}

    const update = req.body

    Product.findOneAndUpdate(filter, update, {new: true}).then((product) => {
        console.log("success");
        res.send(product);
  }).catch(err => {
       console.log("err", err);
       res.status(500).send(err);
  })

});

here's an example of req.body. I've only updated the title and catergory on the frotnend meaning everything else is blank. When it saves in the DB it ony updates the title and catergory and leaves everything else blank. I would like it to not insert the blank ones into the DB and leave the fields as they are

{
  prodId: 'iPhone 111001200',
  title: 'iPhone 11 Pro',
  manufacturer: '',
  catergory: 'Electronics',
  price: '',
  quantity: ''
}

Here's my model

const mongoose = require("mongoose");

const Product = mongoose.model(
  "Product",
  new mongoose.Schema({
    title: String,
    manufacturer: String,
    price: String,
    catergory: String,
    quantity: String,
    prodID: String, 
    images: Array
  })
);

module.exports = Product;
Share Improve this question edited May 9, 2022 at 17:47 noo23r asked May 9, 2022 at 16:27 noo23rnoo23r 991 silver badge7 bronze badges 7
  • On the update part, use $set to define the fields you want to update – nimrod serok Commented May 9, 2022 at 16:29
  • like {$set: update}, I tried using that but no luck – noo23r Commented May 9, 2022 at 16:39
  • {$set: {age: 7, size: 9}} – nimrod serok Commented May 9, 2022 at 16:55
  • but I want to set the specific details the user enters on the frontend so it could change everytime – noo23r Commented May 9, 2022 at 17:18
  • Sure this is only an example. – nimrod serok Commented May 9, 2022 at 17:28
 |  Show 2 more ments

2 Answers 2

Reset to default 5

Something like this then:

const update = {};
for (const key of Object.keys(req.body)){
    if (req.body[key] !== '') {
        update[key] = req.body[key];
    }
}
test.findOneAndUpdate(filter, {$set: update}, {new: true}).then((product) => {
        console.log("success");
        res.send(product);
  }).catch(err => {
       console.log("err", err);
       res.status(500).send(err);
  })}

You should use the $set only to update the fields that you want to update. In your case, the fields that are not ''.

This function converts your payload into mongoose update query

    function convertObject(obj, parentKey = '') {
  // Create an empty result object
  const result = {};

  // Iterate over the keys of the original object
  for (const key in obj) {
    // Check if the value is an object
    if (typeof obj[key] === 'object') {
      // Call the function recursively to convert the nested object
      // Pass the parent key as an argument to append it to the nested keys
      Object.assign(result, convertObject(obj[key], `${parentKey ? `${parentKey}.` : ''}${key}`));
    } else {
      // Add the key to the result object with the same value
      // Use the parent key to create the full key in the format key1.key2.key3...
      result[`${parentKey ? `${parentKey}.` : ''}${key}`] = obj[key];
    }
  }

  // Return the result object
  return result;
}

// Test the function
const originalObject = { doc: { sub_doc: { nested_doc: 'text' } } };
console.log(convertObject(originalObject));
// Output: { 'doc.sub_doc.nested_doc': 'text' }

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论