Mongoose sparks a confrontation following the preservation of a single document in the database

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...');

Answer №1

Model.js

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
mongoose.connect('mongodb://localhost/webservice', function(err){
if(err){
  throw err; 
}else{
  console.log('Connected to database');
}
});
var UserSchema = mongoose.Schema({
name: String,
email: String,
city: String,
age: String
});
var User = mongoose.model('users', UserSchema);
module.exports = User;

Index.js

var app = require('express')();
var User = require('./model');

app.post('/User',function(req, res){
    var Newuser = req.body.user;

    User.create(Newuser, function(err, user){
        res
        .status(201)
        .json({
            user : user
        });

    })
})

Server.js

var express = require('express');
var bodyParser = require ('body-parser');
/**
*   Variables
*/
var  server= module.exports = express();

/**
*   Middleware
*/
server.use(bodyParser.json('aplication/json'))

/** 
*   Routes
*/

 var users = require('./lib/users');
 server.use(users);


 if(!module.parent){
  server.listen(4000, function(){
  console.log("Server is listening on http://localhost:4000")
  });

  } else {
   module.exports = server;
  }

Project Structure

/Project
 /lib
    /users
          -index.js
          -model.js
 server.jse

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Reorganize a list based on another list without generating a new list

Among the elements in my HTML list, there are items with text, input fields, and tables. I also have a specific order list like [3,1,2,0]. Is it feasible to rearrange the items in the HTML list on the page based on this order list without generating a new ...

Is it possible to interpret all events from multiple perspectives?

Is it possible to listen for events in three different ways? This example shows how we can listen for the load event: 1. <body onload="doSomething();"> 2. document.body.onload = doSomething; 3. document.body.addEventListener('load', doS ...

Deselect all event listeners excluding the ones specified in Socket.io

I have a node.js application using socket.io to dynamically load external modules, referred to as "activities," in real-time. Each module binds its own events to the sockets, so when switching from one module to another, I need to remove all event listene ...

Deploying SSL certificate and key in NodeJS/Express on AWS EC2 instance: A step-by-step guide

Recently delving into Node.js & Express.js to develop a web API service, I found myself needing to enable HTTPS using the following code: const server = https .createServer({ key: fs.readFileSync('./cert/myservice.key'), cert: fs.readF ...

What steps do I need to take to develop a CLI application similar to ng, that can be installed globally on the system

Upon installing npm i ng -g How does the system determine the installation path? I am interested in creating an application that can be installed and executed similarly. ...

Is there a way to manipulate the DOM without relying on a library like jQuery?

My usual go-to method for manipulating the DOM involves jQuery, like this: var mything = $("#mything"); mything.on("click", function() { mything.addClass("red"); mything.html("I have sinned."); }); Now I am looking to achieve the same result usin ...

Using Angular to store checkbox values in an array

I'm currently developing a feature that involves generating checkboxes for each input based on the number of passengers. My goal is to capture and associate the value of each checkbox with the corresponding input. Ultimately, I aim to store these valu ...

Creating specialized paths for API - URL handlers to manage nested resources

When working with two resources, employees and employee groups, I aim to create a structured URL format as follows: GET /employees List employees. GET /employees/123 Get employee 123. GET /employees/groups List employee groups. GET /employees/groups/123 ...

Tips for navigating to a different route during the ngOnInit lifecycle event

How can I automatically redirect users to a specific page when they paste a URL directly into the browser? I would like users to be directed to the /en/sell page when they enter this URL: http://localhost:3000/en/sell/confirmation Below is the code I am ...

Tips on accessing information from DynamoDB using a different column as the reference key

I am currently attempting to retrieve data based on an address from the table. I am working within the Express environment for this task. Any assistance on how to extract data using the address instead of the primary ID would be greatly appreciated. ...

What is the process for halting the Node.js (Express) server running in Hyper Terminal?

After closing hyper terminal when a server (port: 1000) based on Express.js and started with nodemon is running, I encountered the following error upon reopening the terminal and attempting to restart the server. I'm unsure if this issue is related to ...

Is there a way to trigger an Axios response without repeated calls or the use of a button?

As I navigate my way through using react and Axios, I encountered an issue with a get request in my code. Currently, I have a button that triggers the request when clicked, but I want to eliminate the need for this button and instead have the information d ...

What is the process for setting a specific version of Node for a project on my local machine?

I am currently facing an issue with setting up Node across multiple developers' machines for a project. The challenge lies in the fact that not all team members are experienced in Node or JavaScript, and we need to ensure that everyone has the correct ...

TokenError: The code has already been utilized - Passport Google OAuth

I am currently attempting to authenticate my application with passportjs using the email strategy. However, I keep encountering a code redeemed error. Upon further investigation, I discovered that the callback is being triggered twice, as shown in the Wire ...

Uploading and saving data to an object in FaunaDB using React hook forms

I am currently facing an issue with uploading/saving data to an object in FaunaDB. Specifically, I am trying to upload a string to a jobProfile object: data: { "jobProfile": { "image": "" "coverImage": " ...

What measures can be taken to restrict users from reaching a page by directly typing the URL?

Is there a way to block users' direct access to a specific page by typing the URL in the address bar? The URL in question is /paymentsuccess as part of the Stripe integration. How can I restrict all users from reaching this page? There is an addition ...

React.js issue with onChange event on <input> element freezing

I am experiencing an issue where the input box only allows me to type one letter at a time before getting stuck in its original position. This behavior is confusing to me as the code works fine in another project of mine. const [name, setName] = useStat ...

What is the best HTTP method to utilize when deleting a sub-document from a MongoDB database?

When working with MongoDB sub-documents, which HTTP verb is appropriate for removing a specific sub-document? Let's consider the following data example: test: 'some value', rooms: [ { id: '1' colour: 'brown ...

What is the best way to display only li elements that possess a specific class utilizing javascript / jquery?

I have a bunch of li's: <ul> <li class="one"></li> <li class="one"></li> <li class="two"></li> </ul> and I want to display only the ones with the class "one" I attempted something like thi ...

There seems to be an issue with the connection between socket.io and the server

Recently, I encountered an issue while hosting my application on OpenShift with a custom domain. The problem arose when socket.io failed to download the client-side script, leading me to resort to using a CDN instead. However, this workaround has caused an ...