I'm struggling to understand what minor mistake I'm making in this code. I have simplified the user schema to just one property, which is name. Initially, when I post the first entry to the database, it gets saved without any issues. However, when I try to save another entry with a different name, I encounter a CONFLICT error. It seems like there is a simple oversight on my end, but I could use an extra pair of eyes to review it.
Below is the schema definition (user.js)
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var userSchema = new Schema({
name: {
type: String
}
});
var User = mongoose.model('User', userSchema);
module.exports = userSchema;
And here is the POST request handler (index.js)
var express = require('express');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var app = express();
// Establishing a database connection and defining models
var conn = require('./db');
var User = conn.model('User');
// Middleware setup
app.use(bodyParser.urlencoded({ extended: false })); // Parse application/x-www-form-urlencoded
app.use(bodyParser.json()); // Parse application/json
// POST - Create a new user
app.post('/api/user', function (req, res) {
console.log(req.body);
User.create(req.body, function (err, user) {
if (err) {
if (err.code === 11000) {
return res.sendStatus(409); // Conflict
} else {
return res.sendStatus(500); // Server error
}
}
res.sendStatus(200); // OK - User created successfully
});
});
app.listen(3000);
console.log('Server is listening...');