我目前正在使用 mongoose 將資料寫入 MongoDB 集合中的檔案,但我不接受空欄位,我已經在檔案中設定了默認值。我呼叫了一個更新函式,它有一些欄位為空,那些欄位已經為空,我不希望他們進行修改。
例子:
const Business = require("./businessModel") //This references the model
const {id, email, name, contactNumber} = args
const business = await Business.findByIdAndUpdate(
{ id},
{
name: ((name != null) ? name : (skip this field))... //HERE
});
我在這里評論的地方,如果名稱不為空,這意味著它存在一個值,那么現在將預定義的架構值名稱設定為新名稱輸入,否則不要更改任何內容,只需跳過該欄位。我已經有了一個替代方法,我先呼叫檔案,然后用檔案的默認值替換它,但這需要一個我認為不是最佳解決方案的檔案呼叫。
uj5u.com熱心網友回復:
看起來您的args變數是具有相關欄位的物件。
您可以只提取id并保留...rest. 然后,您可以過濾此rest物件的空屬性。
// mock
const args = { id: 1, name: null, email: 'email@domain', contactNumber: 4 };
//const Business = require("./businessModel") //This references the model
const { id, ...rest } = args;
const update = Object.fromEntries(Object.entries(rest).filter(([, v]) => v != null));
console.log(update);
//const business = await Business.findByIdAndUpdate({id}, update);
此處物件屬性過濾的更多選項:Remove blank attributes from an Object in Javascript
注意:NULL不存在,javascript 中的 null 物件是小寫的null。請參閱:為什么將 NULL 與邏輯運算子一起使用會在 JS 中引發錯誤
uj5u.com熱心網友回復:
嘗試使用更新驗證器。因此,在您的情況下,請檢查namefield 中是否有值=== null,并根據需要處理錯誤回應。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/324342.html
標籤:javascript json MongoDB 猫鼬
上一篇:在沒有服務器的情況下從HTMLHead讀取JSON檔案
下一篇:RADServerDelphi-由于Json轉換后元音發生變異,使用savetostream和loadfromstream不起作用
