将字符串数组作为node.js和mongodb中的一个参数发布

时间:2016-07-05 09:52:41

标签: node.js mongodb

我对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才能持久化?

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()查找日期,但你的语法看起来很好,所以我猜它已经正确存储了。