Mongoose change _id to id Nodejs Express API

Tutorial “Mongoose change _id to id in Returned Response – Node.js/Express application example”

In the post, I show how to change _id to id in returned response when using Mongoose ODM with Node.js/Express RestAPIs application example.

* Technologies:
– Node.js/Express
– Mongoose ODM
– MongoDB

Project Goal – Mongoose change _id to id

Mongoose ODM uses _id attribute to identiy an Object’s id:

Nodejs Restapi Mongoose Convert _id to id to response client initial data
Nodejs Restapi Mongoose Convert _id to id to response client initial data

How to change _id to id in RestAPI’s returned response?

-> In Mongoose model, we can implement a method transform to resolve it:


const mongoose = require('mongoose');
var Schema = mongoose.Schema;
 
var bookSchema = new Schema({
    title: String,
    author: String,
	description: String,
	published: String	
});

bookSchema.method('transform', function() {
    var obj = this.toObject();

    //Rename fields
    obj.id = obj._id;
    delete obj._id;

    return obj;
});

module.exports = mongoose.model('Book', bookSchema); 

-> Result:

Express Request get All Customers
Express Request get All Customers

Let’s practice!

Set up Nodejs/Express project

Init package.json by cmd: npm init

Install express, mongoose: $npm install express mongoose --save

-> now package.json file:


{
  "name": "nodejs-restapis-mongoose",
  "version": "1.0.0",
  "description": "Nodejs-RestAPI-Mongoose",
  "main": "server.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [
    "Nodejs",
    "RestAPI",
    "Mongoose"
  ],
  "author": "ozenero.com",
  "license": "ISC",
  "dependencies": {
    "express": "^4.16.4",
    "mongoose": "^5.4.2"
  }
}

Setting up Mongoose connection

Open file ./app/config/mongodb.config.js, add the mongodb database configuration:


module.exports = {
    url: 'mongodb://localhost:27017/nodejs-demo'
}

Create Nodejs Express Mongoose model

./app/model/book.model.js file:


const mongoose = require('mongoose');
var Schema = mongoose.Schema;
 
var bookSchema = new Schema({
    title: String,
    author: String,
	description: String,
	published: String	
});

bookSchema.method('transform', function() {
    var obj = this.toObject();

    //Rename fields
    obj.id = obj._id;
    delete obj._id;

    return obj;
});

module.exports = mongoose.model('Book', bookSchema); 

Define Nodejs Express RestAPIs Router

Now we define Book’s routes in ./app/route/book.route.js file as below code:


module.exports = function(app) {
 
    const books = require('../controller/book.controller.js');
	
    // Retrieve all Books
    app.get('/api/books', books.findAll);
 
    // Retrieve a single Book by Id
    app.get('/api/books/:bookId', books.findOne);
}

Implement Nodejs Express RestAPI Controller

In the tutorial “Mongoose change _id to id”, we implement Book’s controller in ./app/controller/book.controller.js file as below sourcecode:


const Book = require('../model/book.model.js');

// FETCH all Books
exports.findAll = (req, res) => {
    Book.find()
    .then(books => {		
		let returnedBooks = [];
		
		for (let i = 0; i < books.length; i++) {
			returnedBooks.push(books[i].transform());
		}
		
		res.send(returnedBooks);
    }).catch(err => {
        res.status(500).send({
            message: err.message
        });
    });
};
 
// FIND a Book
exports.findOne = (req, res) => {
    Book.findById(req.params.bookId)
    .then(book => {
        if(!book) {
            return res.status(404).send({
                message: "Book not found with id " + req.params.bookId
            });            
        }

        res.send(book.transform());
    }).catch(err => {
        if(err.kind === 'ObjectId') {
            return res.status(404).send({
                message: "Book not found with id " + req.params.bookId
            });                
        }
        return res.status(500).send({
            message: "Error retrieving Book with id " + req.params.bookId
        });
    });
};

Nodejs Express Server.js

Now we define server.js file for Nodejs/Express server running at 8080 port as below sourcecode:


var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.json())
 
// Configuring the database
const dbConfig = require('./app/config/mongodb.config.js');
const mongoose = require('mongoose');
 
const Book = require('./app/model/book.model.js');
 
mongoose.Promise = global.Promise;
 
// Connecting to the database
mongoose.connect(dbConfig.url)
.then(() => {
    console.log("Successfully connected to MongoDB.");    
	initial();
}).catch(err => {
    console.log('Could not connect to MongoDB.');
    process.exit();
});
 
require('./app/route/book.route.js')(app);
 
// Create a Server
var server = app.listen(8080, function () {
 
  var host = server.address().address
  var port = server.address().port
 
  console.log("App listening at http://%s:%s", host, port)
 
})

function initial(){
	Book.create({
		title: "Origin",
		author: "Dan Brown",
		description: "Origin thrusts Robert Langdon into the dangerous ntersectio of humankind's two most enduring questions",
		published: "2017"	
	});
	
	Book.create({
		title: "Happy Potter and the Deathly Hallows",
		author: "J.K. Rowling",
		description: "The seventh and final novel of the Harry Potter series.",
		published: "2007"	
	});
	
	Book.create({
		title: "The 100-Year-Old Man Who Climbed Out the Window and Disappeared",
		author: "Jonas Jonasson",
		description: "",
		published: "2009"	
	});
}

Read More

Nodejs Express Run & Check Results

– Run MongoDB mongod.exe
– Run Nodejs application: npm start

Nodejs Restapi Mongoose Convert _id to id to response client initial data
Nodejs Restapi Mongoose Convert _id to id to response client initial data

Express get all customers:

Express Request Get All customers
Express Request Get All customers

– Express get a customer by id:

Nodejs Expresss Get a Customer by Id
Nodejs Expresss Get a Customer by Id

Sourcecode

mongoose-nodejs-example-_id-to-id

– Github Sourcecode:

nodejs-change-_id-to-id-github-sourcecode

Upload and Read Excel File in Node.js

Tutorial “Upload and Read Excel File in Node.js – Express RestAPI Upload/Import Download/Export Multiple Excel files”

In the tutorial, I will introduce how to build a Nodejs/Express RestAPIs application to upload/import and download/extract data from multiple Excel files to MySQL or PostgreSQL database by:

  • Express is used to build Nodejs RestApis
  • Multer is used to upload/download Excel files
  • Sequelize ORM is used to manipulate data with MySQL/PostgreSQL
  • Exceljs is used to save data objects to Excel file
  • Read-excel-file is used to parse Excel file to data objects
Related posts:


Continue reading “Upload and Read Excel File in Node.js”

Angular Nodejs MongoDB CRUD Example

In the tutorial, I introduce how to build an “Angular Nodejs MongoDB CRUD Example RestAPIs” project with the help of Express Web Framework and Mongoose ODM for POST/GET/PUT/DELETE requests with step by step coding examples:

– I draw a fullstack overview Diagram Architecture from Angular Frontend to MongoDB database through Nodejs RestAPI backend.
– Develop Nodejs CRUD RestAPIs with the supporting of Express Rest Framework.
– Implement Angular CRUD application with the Angular Httpclient to do CRUD request (Post/Get/Put/Delete) to Nodejs Backend APIs.
– I create a testsuite with a number of integrative testcases with CRUD RestAPI requests from Angular HttpClient to do CRUD requests to Nodejs RestAPIs Server and save/retrieve data to MongoDB database.

Related posts:


Continue reading “Angular Nodejs MongoDB CRUD Example”

Angular 11 Node.js Mysql Crud Example

Tutorial: “Angular 11 Node.js Mysql Crud Example – using Express and Sequelize ORM”

In the tutorial, I introduce how to build an Angular 11 Node.js MySQL CRUD Example RestAPIs Fullstack Project with the help of Express Web Framework and Sequelize ORM for POST/GET/PUT/DELETE requests with step by step coding examples.

Related posts:


Continue reading “Angular 11 Node.js Mysql Crud Example”

React Node Jwt Authentication without Redux – using LocalStorage and Axios

Tutorial: React Node Jwt Authentication (without Redux) – using LocalStorage and Axios (plus interceptor) in React application and Express + Sequelize + MySQL/PostgreSQL in Nodejs backend solution.

JSON Web Token (JWT) is an open standard (RFC 7519) that defines a compact and self-contained way for securely transmitting information between parties as a JSON object. And “How to build Reactjs Nodejs Jwt Token Based Authentication Example?” is one of the most common questions for Nodejs development world. So in the tutorial, I introduce how to implement an application “Reactjs JWT Nodejs token Authentication Example” with details step by step and 100% running sourcecode.

– I give you an Epic of the application, a fullstack excutive flow from frontend (Reactjs) to backend (Nodejs/Express) to database (MySQL/PostgreSQL) with overall architecture diagram.
– I give you a layer diagram of Reactjs Jwt Application with LocalStorage and Axios (plus Interceptor)
– I guide you detail-steps how to implement a security Jwt Token Nodejs backend.
– I guide you step by step how to develop a Reactjs Jwt Authentication application.
– Finally, I do an integrative testing from Reactjs Jwt Authentication application to jwt Nodejs Security RestAPIs.

Related posts:


Continue reading “React Node Jwt Authentication without Redux – using LocalStorage and Axios”