我正在使用express和nodejs开发一个API,该API使用mongoose将数据存储在mongoDB中,以下是我设计的架构。
const MessagesSchema = new mongoose.Schema(
{
readReceipt: {
type: String,
required: [true, "Read Receipt Mandatory"],
enum: {
values: ["sent", "received", "read"],
message: `Ivalid value {value}`,
},
},
messageContent: { type: String },
sentBy: {
type: mongoose.Schema.Types.ObjectId,
ref: "Users",
required: [true, "Sender cannot be Empty"],
},
sentTo: {
type: [mongoose.Schema.Types.ObjectId],
ref: "Users",
required: [true, "At Least One senderId required"],
},
},
{ timestamps: true }
);
以下是数据存储在 mongoDB 中时得到的输出。
{
"readReceipt": "sent",
"messageContent": "Test Message 4",
"sentBy": "6728a8b1b6fd6ebeac8e0fa5",
"sentTo": [],
"_id": "672b2539d7f2f99e8f9ef738",
"createdAt": "2024-11-06T08:13:45.080Z",
"updatedAt": "2024-11-06T08:13:45.080Z",
"__v": 0
}
sentTo 字段是一个 ObjectId 的数组,如上面的输出中的 sendTo 字段被存储为一个空数组,我希望它在没有传递值时通过错误,我尝试传递 required: true 但它不起作用。我在互联网上搜索该问题,但找不到任何具体内容。
我正在使用
猫鼬:“8.8.0”
表达:“4.21.1”
节点:“18.18.0”
我尝试在架构中添加 required:true 但它不起作用,我希望它在存储空值时会出现错误。
此问题的任何解决方案表示赞赏,谢谢
请尝试为sentTo字段添加验证/验证器
sentTo: {
type: [mongoose.Schema.Types.ObjectId],
type: [mongoose.Schema.Types.ObjectId],
ref: "Users",
ref: 'Users',
required: [true, "At Least One senderId required"],
required: [true, 'At Least One senderId required'],
validate: {
validator: function (v) {
return v.length > 0;
},
message: 'The sentTo array cannot be empty',
},