我对node.js和REST一般都很新。我的模型有以下模式:
"properties": {
"name": {
"type": "string",
"description": "student name"
},
"family": {
"type": "string",
"description": "family name"
},
"subjects": {
"type": "array",
"description": "list of subjects taken",
"minItems": 1,
"items": { "type": "string" },
"uniqueItems": true
}
前两个属性是直接的,因为它们是字符串。但我很困惑如何发布subjects
的数组。我已经将模型编码为:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var StudentSchema = new Schema({
name: String,
family: String,
subject: [String]
});
module.exports = mongoose.model('Student', StudentSchema);
我不知道我是否做得对。当我尝试使用POSTMAN进行POST时,它会保留记录,但我不知道它是仅存储为数组还是字符串。我该如何验证?如何添加一个验证,即数组长度必须> 1才能持久化?
答案 0 :(得分:1)
首先是验证部分
var StudentSchema = new Schema({
name: String,
family: String,
subject: {
type: [String],
validate: [arrayLengthGreaterOne, '{PATH} size has to be > 1']
}
});
function arrayLengthGreaterOne(val) {
return val.length > 1;
}
“不知道它是如何存储的”是什么意思?
我只是通过mongo本身的db.find()
查找日期,但你的语法看起来很好,所以我猜它已经正确存储了。