1

I am very new to node.js and REST in general. My model has following schema:

"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
}

First two properties are straight forward as they are string. But I am confused how to post an array for subjects. I have coded the model like this:

var mongoose     = require('mongoose');
var Schema       = mongoose.Schema;

var StudentSchema   = new Schema({
    name: String,
    family: String,
    subject: [String]
});

module.exports = mongoose.model('Student', StudentSchema);

I don't know whether I have made it correct or not. When I tried to POST using POSTMAN, it persisted the record, but I don't know whether it was stored as an array or String only. How do I verify that? How do I add a validation that length of the array has to be >1 for persisting?

1
  • use the shell or a tool such as robomongo to find the data in your database Commented Jul 5, 2016 at 10:59

1 Answer 1

1

First the validation part

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;
}

What do you mean by "don't know how it was stored?"

I would just look up the date via db.find() in mongo itself but your syntax looks fine so I guess it got stored correctly.

Sign up to request clarification or add additional context in comments.

1 Comment

How do I access this "{PATH} size has to be > 1" message? I want to different error message for different errors

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.