Search code examples
node.jsexpressmongoose-schema

Express JS / Mangoose : Bad Request error creating an object


I want to create a Mangoose object from form data.

Here is the JS code of the HTML page :

const easyMDE = new EasyMDE({element: document.getElementById('body_content')});

    $(document).ready(function () {
        $("form").submit(function (event) {
            var formData = {
                'body_content': easyMDE.value(),
                'name': $('input[name=name]').val(),
                'seo_title': $('input[name=seo_title]').val(),
                'image_url': $('input[name=image_url]').val(),
                'template': $('input[name=template]').val(),
                'type': $('input[name=type]').val(),
                'slug': $('input[name=slug]').val(),
                'seo_description': $('input[name=seo_description]').val()
            };

            $.ajax({
                type: "POST",
                url: "/nxapi/page/",
                data: formData,
                dataType: "json",
                encode: false,
            }).done(function (data) {
                console.log(data);
            });

            event.preventDefault();
        });
    });

And here is the controller code :

const Page = require('../models/Page');

exports.createPage = (req, res, next) => {
  const page = new Page({
    type: req.body.type,
    name: req.body.name,
    template: req.body.template,
    image_url: req.body.image_url,
    seo_title: req.body.seo_title,
    seo_description: req.body.seo_description,
    body_content: req.body.body_content,
  });
  page.save().then(
    () => {
      res.status(201).json({
        message: 'Post saved successfully!'
      });
    }
  ).catch(
    (error) => {
      res.status(400).json({
        error: error
      });
    }
  );
};

And my model :

const mongoose = require('mongoose');

const pageSchema = mongoose.Schema({
  type: { type: String, required: true },
  name: { type: String, required: true },
  template: { type: String, required: true },
  slug: { type: String, required: true },
  image_url: { type: String },
  seo_title: { type: String },
  seo_description: { type: String },
  body_content: { type: String },
  created: { type: Date, default: Date.now() },
  modified: { type: Date, default: Date.now() },
});

module.exports = mongoose.model('Page', pageSchema);

When I submit the form, I've got this error :

Page validation failed: slug: Path `slug` is required.

I've tried to encode the form data in JSON in another way, still I check the data submitted and everything is well received by the controller function. I can console.log(req.body.type) for exemple, and the value is correctly shown.

If I console.log the req.body variable, here's what I've got :

{
  body_content: 'Test',
  name: 'Test',
  seo_title: 'Test SEO',
  image_url: 'image.jpg',
  template: 'article-v1',
  type: 'article',
  slug: 'test',
  seo_description: 'Description SEO'
}

I've added in my app.js :

const bodyParser = require("body-parser")
app.use(bodyParser.urlencoded({ extended: true }));

I don't understand what I did wrong. Could someone help me please ?

Many thanks,


Solution

  • You need to specify slug field when you create an object.

      const page = new Page({
        type: req.body.type,
        name: req.body.name,
        template: req.body.template,
        image_url: req.body.image_url,
        seo_title: req.body.seo_title,
        seo_description: req.body.seo_description,
        body_content: req.body.body_content,
        slug: req.body.slug
      });