簡體   English   中英

使用 findOneAndUpdate() 時,如何在未提供值的情況下保持字段不變(而不是用 null 覆蓋)?

[英]When using findOneAndUpdate(), how to leave fields as is if no value provided (instead of overwriting with null)?

用戶可以選擇更新幾個值中的任何一個 - 但是,如果他只傳入{ name: "new name" } ,電子郵件和密碼字段也會更新但為“null”。

我怎樣才能只更新 req.body 中實際提供的字段,其余的保持原樣?

這是同時指定可以使用 POST 請求更新哪些字段 - 我避免只傳遞 req.body 因為我想限制這一點。

我的代碼看起來像:

db.User.findOneAndUpdate({_id: req.params.id}, { 
        name: req.body.name,
        email: req.body.emaill, 
        password: req.body.password
})

使用類似 name: req.body.name && req.body.name來檢查值是否未定義也會被“null”覆蓋。

謝謝!

首先准備更新對象:

let params = { 
        name: req.body.name,
        email: req.body.emaill, 
        password: req.body.password
};

for(let prop in params) if(!params[prop]) delete params[prop]; //This will not handle intentionally setting to false, empty string, null, 0, or other falsey values.

db.User.findOneAndUpdate({_id: req.params.id}, params);

或者,如果您的屬性名稱匹配:

let params = {};

for(let prop in req.body) if(req.body[prop]) params[prop] = req.body[prop];

db.User.findOneAndUpdate({_id: req.params.id}, params);

const resu=await this.store.company.findByIdAndUpdate(companyId,
{ $set: { name,dba,description,foundedYear,contactInfo,clients,eVerified,socialMedia}, },
{new:true,omitUndefined:true},)

使用 omitUndefined:true 選項

這個怎么樣?

db.User.findOneAndUpdate({_id: req.params.id}, req.body)

如果您的請求看起來與您的示例( { name: "new name" } )完全一樣,那么這應該具有預期的效果。

如果您計划驗證收到的數據,您可以創建包含所有有效字段的更新對象。 例如:

// Example post
const req = {
    body: {
        name: "First Last",
        email: "app@app.com",
        somethingElse: "I snuck in another update!"
    }
}

// Create update obj
const update = {}

// Destrcture the body to make if statments smaller to read
const {name,email,password} = req.body

// Test all values and add valide ones to update
if(name !== undefined && typeof name === 'string') {
    update.name = name
}

if(email !== undefined && typeof name === 'string') {
    update.email = email
}

if(password !== undefined && typeof password === 'string') {
    update.password = password
}

console.log(update)

現在在您的 Mongo 更新中使用該更新對象。 當然,您希望調整驗證以檢查諸如電子郵件格式或密碼要求之類的內容,以及可能更清晰地將它們放入函數中,但您明白了。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM