这是我的架构,当我在提交一个"博客"之前将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
没有任何价值,并且它没有设置默认值。
答案 0 :(得分:1)
我通过添加如下if语句解决了这个问题:
if(image === '') {
image = undefined;
}
答案 1 :(得分:0)
清除空字符串以及您认为不需要的任何其他内容。也许在将对象传递给mongo之前尝试使用lodash函数。
_.pickBy(updateObject, v => v !== null && v !== undefined && v !== ""); // removes all null, undefined and empty string values
答案 2 :(得分:0)
我也遇到类似的困难,因此我选择使用具有默认值的变量。当您尝试执行POST请求时,它将包括在内。
var image = req.body.image || "some default value";
假设用户未输入任何内容,则在将数据发送到后端时,默认情况下其值空。