SOLVED - NodeJS API: Data not being saved correctly on CREATE endpoint

As part of a short online NodeJS course assignment, I have built a small MVC pattern API with INDEX, CREATE, UPDATE and DELETE endpoints. Whilst it is showing no errors when it’s run, there’s a problem when creating a new record in MongoDB in that the JSON data objects are not being saved, but the associated ID and timestamps are.

The JSON data objects look like this.

{
    "balance": 1000,
    "name": "savings"
}

I’ve been testing it with Insomnia (a POSTman equivalent) and CURL statements at the CLI, but I’m either getting neither property saved, or if I modify the model.js slightly, I’ll get the balance property recorded as NaN, but no name property - see comment in code below.

At the moment, I’m not spotting what’s going wrong, and it’s not helping me out with any useful error messages.

You can find the full solution on my repo at Github - [rest_api_with_mongodb](https://github.com/christopherallanperry/rest_api_with_mongodb.

My server.js (app) file contains:

const express       =  require("express");
const logger        =  require("morgan");
const errorhandler  =  require("errorhandler");
const bodyParser    =  require("body-parser");
const mongoose      =  require("mongoose");
const app           =  express();
const config        =  require("./config/config");
const routes        =  require("./config/routes");

mongoose.connect(config.db);

// Use morgan for logging
app.use(logger("dev"));

// Setup body-parser to read HTTP body
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));


app.use(errorhandler());

app.use("/", routes);
app.listen(config.port, () => {
  console.log(`Express has started on port: ${config.port}`);
});

My controllers/account.js contains

I’ve removed the other endpoints for the purposes of this thread

const Account = require('../models/account');

function accountsCreate(req, res) {
  Account.create(req.body.account, (err, account) => {
    if (err) return res.status(500).json({ message: '500 server error - contact the server administrator.' });
    if (!account) return res.status(500).json({ success: false, message: 'Please send the correct information to create an account.' });
    return res.status(201).json(account);
  });
}

module.exports = {
  create: accountsCreate
};

models/account.js contains

const mongoose = require("mongoose");

const accountSchema = mongoose.Schema({
  name: { type: String },
  balance: { type: Number }
}, {
  timestamps: true
});

// Ensure that the number is saved as an integer but returned as a float
// IF THIS LINE IS COMMENTED OUT, ONLY TIMESTAMPS ARE STORED
accountSchema.path("balance")
  .get(value => (value/100).toFixed(2))
  .set(value => value*100);

// Unsure that the object is sent as JSON
accountSchema.set("toJSON", { getters: true, setters: true, virtuals: false });

module.exports = mongoose.model("Account", accountSchema);

config/config.js

const port = process.env.PORT || 3000;
const db = process.env.MONGODB_URI || "mongodb://localhost:27017/edx-course-db";

module.exports = {
  port,
  db
};

config/routes.js

const express   = require("express");
const router    = express.Router();

const accounts  = require("../controllers/accounts");

router.route("/accounts")
 .get(accounts.index)
 .post(accounts.create);


module.exports = router;

Problem solved. I’d set my controller up to expect a slightly different JSON data structure. This line…

Account.create(req.body.account, (err, account) => {

needed to be…

Account.create(req.body, (err, account) => {

The the original would have worked if I’d had the JSON structure as…

{
    "account": {
        "balance": 1000,
        "name": "savings"
    }
}

pay attention to the details Christopher

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.