簡體   English   中英

為什么當沒有輸入任何內容時,`default` 值在 mongoose 模式中不起作用?

[英]Why doesn't the `default` value work in mongoose schema when nothing was entered?

這是我的架構,當我在提交“博客”帖子之前將 HTML 輸入字段留空時,圖像default值似乎不起作用。

var blogSchema = new mongoose.Schema({
    title: String,
    image: {
        type: String,
        default: "some image url"
    },
    body: String,
    created: {
        type: Date,
        default: Date.now
    }
});

這是進入數據庫的輸入。

{ __v: 0,
  title: '',
  body: '',
  _id: 583af591c460fca539b8f787,
  created: 2016-11-27T15:02:41.613Z,
  image: '' }

我不明白問題是什么,因為image沒有任何值並且它沒有設置默認值。

我通過添加 if 語句解決了這個問題,如下所示:

if(image === '') {
  image = undefined;
}

清除空字符串和任何您認為不想要的東西。 也許在將對象傳遞給 mongo 之前嘗試這個 lodash 函數。

_.pickBy(updateObject, v => v !== null && v !== undefined && v !== ""); // removes all null, undefined and empty string values

我遇到了類似的困難,我選擇使用具有默認值的變量。 當您嘗試執行 POST 請求時,它將被包含在內。

var image = req.body.image || "some default value";

假設用戶沒有輸入任何內容,當數據發送到后端時,默認情況下它的值為null

暫無
暫無

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

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