[英]how to only update specific fields and leave others with the previous values in findandupdate with Mongoose
我使用 Mongoose 創建了一個更新函數。 但是,每當我使用 findOneAndUpdate 更新數據時。 它只更新輸入的字段並使其他字段現在為空或為空。 我希望這樣當用戶更新並且他們不更新文件時,它應該保持原樣而不是現在為空。 基本上只更新輸入的字段。
這是我的路線
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);
})
});
這是 req.body 的一個例子。 我只更新了前端的標題和類別,這意味着其他所有內容都是空白的。 當它保存在數據庫中時,它只會更新標題和分類並將其他所有內容留空。 我希望它不要將空白的插入數據庫並將字段保留原樣
{
prodId: 'iPhone 111001200',
title: 'iPhone 11 Pro',
manufacturer: '',
catergory: 'Electronics',
price: '',
quantity: ''
}
這是我的模型
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;
然后是這樣的:
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);
})}
您應該僅使用$set
來更新您想要更新的字段。 在您的情況下,不是''
的字段。
此函數將您的有效負載轉換為 mongoose 更新查詢
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' }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.