Mongoose: generate empty json from model

Mongoose: generate empty json from model

Problem

I have such schema in my mongoose category model.

var categorySchema = new Schema({
    title: String,
    description: String,
    order: Number
});

How can I generate empty json with these params to use it in my textarea when I want to add new category? This is example what do I want to get:

{
    "title": "",
    "description": "",
    "order": 
}

So I will simply fill these fields and then make POST request to my API and insert category data to database.

Problem courtesy of: user3215609

Solution

You can create a static method for the category schema that will output a data object to send back to the client to fill out your textarea. Something like:

var mongoose = require('mongoose');

var categorySchema = new mongoose.Schema({
  title: String,
  description: String,
  order: Number
});

categorySchema.statics.getSkeleton = function () {
  var data = {};
  Object.keys(categorySchema.paths).forEach(function (path) {
    return path !== '_id' ? data[path] = "" : false;
  });
  return data;
}

And then you can consume it thusly:

var textAreaDefaults = Category.getSkeleton();
Solution courtesy of: srquinn

Discussion

Leave a Reply

Your email address will not be published. Required fields are marked *