猫鼬创建附加文档来存储默认值

Mongoose creating additional document to store default values

当用户创建笔记时,Mongoose API 会创建一个包含用户笔记值的文档,然后创建一个仅包含默认参数的附加文档。有没有办法从数据库中删除它?

我的 Note 架构是这样的:

var NoteSchema = new mongoose.Schema({
    title: String,
    text: String,
    color: {
        type: String,
        default: "white", <--- default
    }
    favorited: {
        type: Boolean,
        default: false,   <--- default
    }
});

mongo 控制台中:

// Document it creates and what I expect
{ 
    "_id": "58795af461e2db2db804997d", 
    "title" : "Testing: Hello", 
    "favorited" : false, 
    "color": "strawberry", 
    "author": { 
        "id": "587950df61e2db2db8049972", 
        "username" : "tester" 
    } 
}
// Additional default (unneccessary) document created:  
{ 
    "_id": "58795af461e2db2db804997e", 
    "favorited": false, <--- from the Schema
    "color": "gray" <--- from the Schema
}

从用户的角度来看,它没有做任何事情,但我不希望它为每个注释创建一个带有默认值的附加文档。我怎样才能摆脱它?

您可以更改您的架构,为 titletext 字段设置 requiredminlength 验证。

var NoteSchema = new mongoose.Schema({
    title: {
        type: String,
        required: true,
        minlength: 15   // <--- Set the minimum title length
    },
    text: {
        type: String,
        required: true,
        minlength: 100   // <--- Set the minimum text length
    },
    color: {
        type: String,
        default: "white",
    }
    favorited: {
        type: Boolean,
        default: false,
    }
});

这将确保如果缺少 title and/or text 则不会保存文档。此外,如果它们的长度小于它们的 minlength 值,则不会保存文档。