"MongoDB Reveals Its True Power: Unveiling the Second

I am facing an issue with the second res.json. I have attempted the following:

res.json({500,message : 'xxxxxx'})

res.send({500,message : 'xxxxxx'})

However, the problem persists. Here is my code snippet:

import mongoose from 'mongoose';
import {Router} from 'express';
import Motor from '../model/motor';

export default({config,db}) =>{
  let api = Router();

  //  '/v1/motor/add'
  api.post('/add',(res,req) => {
    let newMotor = new Motor();
    newMotor.title = req.body.title;

    newMotor.save(err = {
       if(err){
          res.json({message : 'error'});
       }
       res.json({message : 'motor saved successfully'});
     });
  });

  return api;
}

Here is the error message being displayed:

SyntaxError: C:/Users/Ali Baltschun/Desktop/motorDB/src/controller/motor.js: Unexpected token, expected , (17:6)
  15 |         res.json({message : 'error'});
  16 |       }
> 17 |       res.json({message : 'motor saved successfully'});
     |       ^
  18 |     });
  19 |   });

Answer №1

res.json is expecting a valid JSON object.

res.json({500,message : 'xxxxxx'})

The line above will result in failure.

It is important to remember to return res.json.

 newMotor.save(err = {
       if(err){
          return res.json({message : 'error'});
       }
       return res.json({message : 'motor saved successfully'});
     });
  });

In order to send a 500 server error code, you can use the following:

res.status(500).json({message : 'error'})

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

Strange Occurrences Linked to Meteor's Iron Router and Pub Sub

Trying to set up a route for a single post page that performs multiple tasks using iron:router Utilizes the template postPage Subscribes to the publications of singlePost, userStatus (displays status and information of the Author of the single post page) ...

Having difficulty fetching a document from MongoDB (using Mongoose) due to a partial match issue

Currently, I am working on a NodeJS project using version 16.14.0, and I am faced with the challenge of filtering a list of documents. While most attributes are simple strings that are easily accessible, I am encountering difficulties with the specialty (o ...

What is the best way to position a semi-circular donut graph in the center?

I am attempting to showcase a doughnut or semi-circle chart within a materialize card, which is a responsive div element. My goal is to present simple data and utilize the chart as a progress bar. I took inspiration from the example provided in the HighCh ...

Paper.js - Applying transparency to shapes that extend beyond set boundaries

I am currently using a simple rectangle as the clipping area for all shapes added to the canvas, and it's working perfectly: var area = new paper.Rectangle( 100, 100, 300, 120 ); var path = new paper.Path.Rectangle(area); group.addChild(path); ...

Display the Express response in an HTML element by utilizing the fetch API

I am currently developing a small node/express project that showcases the bcyrpt hashed value of user input. While I have been successful in displaying the hashed value in the server's console.log, I am facing difficulties in injecting this value into ...

javascript console to automate clicking and pressing keys

I'm in need of assistance. I'm looking to create a script that simulates pressing the Enter button 2000 times in a console and auto clicks 2000 times with no delays. I also need a key to stop this action. Can anyone help me out? Thanks in advance ...

Error in Continuous Integration for Angular 4: Unable to access property 'x' of an undefined variable

i am trying to display some data on the form but encountering an error: TypeError: Cannot read property 'title' of undefined below is my component code : book:Book; getBook(){ var id = this.route.snapshot.params['id']; ...

Is there a way to completely clear a form using jQuery in JavaScript?

I have a functioning script that sends emails via Ajax and PHP. However, I am also looking to reset the form after sending an email. Below is my jQuery code: <script src="http://code.jquery.com/jquery-latest.js"></script> <script> $(doc ...

Switching the navigation menu using jQuery

I am looking to create a mobile menu that opens a list of options with a toggle feature. I want the menu list to appear when the toggle is clicked, and I also want to disable scrolling for the body. When the toggle menu is clicked again, the list should c ...

Using a pool.query with async/await in a for-of loop for PostgreSQL

While browsing another online forum thread, I came across a discussion on using async/await with loops. I attempted to implement something similar in my code but am facing difficulties in identifying the error. The array stored in the groups variable is f ...

Struggling to locate the 'babel-runtime/regenerator' module? Consider importing it locally versus from NPM for a seamless integration

I've been encountering issues with my babel configuration while working on an NPM module that utilizes ES6 features like async/await, static class methods, and import/export. Initially, I faced the common error ReferenceError: regeneratorRuntime is n ...

Unlock the potential of nested associative arrays in MySQL 8 by extracting them into rows using JSON_TABLE

I have been struggling to extract data from a MySQL table with a JSON column containing nested rows, each with a unique key. Despite using MySQL 8 and attempting the json_table function, I have had no success in retrieving the desired information. Below i ...

Having trouble performing Bulkwrite operation on a mongo collection and unable to update it successfully

I have a MongoDB collection with the following fields: Sno1 Sno2 Location The data in this collection is structured as follows: Sno1 Sno2 Location -------------------------------- 1000 2000 Hyderabad My goal is to update the location to ' ...

Accessing an array in Scala Play Json using JsPath

import play.api.libs.json._ val jsonData: JsValue = Json.parse(""" { "name" : "Independence", "foundingFathers" : [ { "name" : { "first": "John", "last": "Adams" }, "country" : "United States" }, { "na ...

What is the best way to sum the numbers in this code snippet?

I'm trying to iterate through an array called arr = [[1,2],4] using for loops to access the numbers. However, I've noticed that I can't seem to add the last number for some reason. Can anyone explain why this is happening? let arr = [[1, ...

Activate the Alert (https://material-ui.com/components/alert/#alert) starting from the React component at the bottom of the hierarchy

When it comes to alerts, a normal alert is typically used like alert("message to be displayed");. However, I prefer using material UI Alerts which return a JSX component. For example: <Alert severity="success">This is a success alert — check it out ...

Utilizing Angular2 Observables for Time Interval Tracking

I'm working on a function that needs to be triggered every 500ms. My current approach in angular2 involves using intervals and observables. Here's the code snippet I've implemented so far: counter() { return Observable.create(observer =&g ...

Waiting for the outcome of a function that calls itself repeatedly

The solve function provided here is designed to sort elements in an array based on their frequency and value. However, when dealing with longer input arrays, it encounters a 'Cannot read property' error which disrupts the sorting process. To add ...

Updating the Highcharts chart when new data is available

Utilizing Highcharts, I am looking to have this chart update every second. Here's my current setup: JSFiddle I've implemented a timer with window.setInterval(updateChart, 1000); which successfully updates data each second. However, I'm uns ...

Strategies for accessing array elements based on category

I am currently working with an array of diverse products var productList = [ { id: '1', category: 'todos', menuName: 'Empanada de Carne, Pollo o Mixta + Café 8oz.', menuPrice: '9.99&a ...