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

Creating a Union Type from a JavaScript Map in Typescript

I am struggling to create a union type based on the keys of a Map. Below is a simple example illustrating what I am attempting to achieve: const myMap = new Map ([ ['one', <IconOne/>], ['two', <IconTwo/>], ['three ...

Issue with Mongoose JS populate method: incomplete object reference returned, only objectId version shown

Whenever I utilize the populate method, I am only receiving the _id value. Below is the controller where I intend for this to happen: show: function(req, res) { User.findOne({ _id: req.params.id }) .populate("roommates") .exec(function(err, user) { i ...

Guide to hosting AngularJS Material documentation on a local server

After gathering the latest angularjs material, I noticed that the links in the document lead to absolute URLs at material.angularjs.org/.... I wish to have access to read the documentation and demonstration content locally. ...

The MUI5 drawer overlapping a modal dialog

Is it possible to use MUI5 to open a side drawer on top of a modal dialog that triggers it? Currently, the dialog triggers the side drawer but it opens behind this. It appears as though a modal dialog (drawer) is attempting to open over an already-opened ...

Storing the outcome of a connection in a variable using Node.js

I am facing an issue with saving a function return in a const so that I can utilize the information outside of the function scope. Below is a snippet of code to better explain my problem: const express = require('express') const app = express() ...

Ways to store a filestream coming from Node.js into AngularJS

When using my express server, I have a post-request set up to retrieve a pdf file from Amazon S3 and then send it back to Angular. This is the endpoint in my express server: var fileStream = s3.getObject(options).createReadStream(); fileStream.pipe(res); ...

Utilizing Material UI's (MUI) date picker in conjunction with react-hook-form offers a

I'm currently developing a form with a date field utilizing MUI and react-hook-form for validation. I have experimented with two different methods of rendering the field, but when I try to submit the form, the expected value is not being returned: Me ...

jQuery carousel displaying a blank slide at the conclusion

I am experiencing an issue with my slideshow where it shows an empty slide after the last element. I suspect that there is something in my script causing this behavior, as it seems to be finding one extra child for the element and adding it as an empty spa ...

Programmatically adding route resolve in Angular using $routeProvider

Is it possible to dynamically add Angular's resolve after it has been initially defined in the app? Let's say we have a setup with routes like this: app.config(['$routeProvider', function ($routeProvider) { $routeProvider ...

`Troubleshooting Firebase Cloud Functions and Cloud Firestore integration`

I previously used the following Firebase Database code in a project: const getDeviceUser = admin.database().ref(`/users/${notification.to}/`).once('value'); Now, I am attempting to convert it for Firestore. My goal is to retrieve my users' ...

Enabling clients to access all static files from a Node.js + Express server

My index.js file serves as a node.js server : var express = require('express'); var app = express(); const PORT = process.env.PORT || 5000; var serv = require('http').Server(app); app.get('/', function(req, res) { res.sen ...

I wonder what might be the root of this Heroku crash with error code H10

After reviewing previous suggestions regarding this issue, such as restarting dynos or ensuring the use of var PORT = process.env.PORT || 3000, I have implemented all of these solutions but my application continues to crash. The app is built using node/exp ...

What is the best method to assign each key in an Object to the corresponding value in another Object?

Suppose I have an object called data: { first: 'Zaaac', last: 'Ezzell', title: 'Mrs', mail: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="83ece6f9f9e6efefb3c3f1e6e7e7eaf7ade ...

Tips for identifying the amount of <ul> elements contained within every div

Dealing with a large file structured in the same way, I am looking for a method to isolate a specific div, determine the number of ul's within it, and then iterate through each one to extract the value of every li element. <div class="experiment ...

Express 4 app.use not functioning properly

My backend setup is fairly straightforward with a few routes. I prefer to keep the route logic separate from the server.js file, but for some reason, when I make a POST request to the route, it returns a 404 error. In the server.js file: // Import necess ...

Is it possible for Angular.js to access a server session attribute?

I am in the process of creating an authentication system with angular.js My goal is to implement a session timeout after a period of inactivity and expire the current session if a user logs in from another device. In both scenarios - 1) idle timeout and ...

Issue in Angular Material: The export 'MaterialComponents' could not be located in './material/material.module'

I'm relatively new to Angular and I am encountering some difficulties when trying to export a material module. The error message that appears is as follows: (Failed to compile.) ./src/app/app.module.ts 17:12-30 "export 'MaterialComponents&ap ...

The incremental BR tag counter seems to be malfunctioning, there appears to be a missing element

Can anyone help me with the following code? I'm trying to add an incremental counter next to each BR tag in a lyric song, but it doesn't seem to be working as expected. <?php $lyrics = "<p>Every time when I look in the ...

Automatically move to the latest message as soon as it is posted

After trying multiple codes and encountering issues, I am attempting to add my message in a textarea that will automatically scroll down. Even though I have my own codes, they don't seem to work properly. I also tried using the code provided Here. ED ...

Is there a way in javascript, jquery, and plupload to dynamically pass a parameter to the URL without needing to reload the page or object?

I've recently taken over a project that utilizes plupload. I am encountering an issue where I need to change the URL of the object after it has been loaded. However, I'm unsure if this is possible and what steps I would need to take to achieve th ...