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

nodejs-restapi-mongoose-convert-_id-to-id-to-response-client---feature-image

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

Related posts:
Crud RestAPIs with NodeJS/Express, MongoDB using Mongoose

Technologies

– Node.js/Express
– Mongoose ODM
– MongoDB

Goal

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

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:

-> Result:

nodejs-restapi-mongoose-convert-_id-to-id-to-response-client---get-all-data

Practice

Project structure:

nodejs-restapi-mongoose-convert-_id-to-id-to-response-client---project-structure

Setting up Nodejs/Express project

Init package.json by cmd:

npm init

Install express, mongoose:

$npm install express mongoose --save

-> now package.json file:

Setting up Mongoose connection

./app/config/mongodb.config.js file:

Create Mongoose model

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

Express RestAPIs
Route

Define Book’s routes in ./app/route/book.route.js file:

Controller

Implement Book’s controller in ./app/controller/book.controller.js file:

Server.js

server.js file:

Run & Check Results

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

nodejs-restapi-mongoose-convert-_id-to-id-to-response-client---initial-data

-> Make requests:

nodejs-restapi-mongoose-convert-_id-to-id-to-response-client---get-all-data

nodejs-restapi-mongoose-convert-_id-to-id-to-response-client---get-a-book

Sourcecode

Nodejs-RestAPIs-Mongoose

By grokonez | January 8, 2019.



Related Posts


Got Something To Say:

Your email address will not be published. Required fields are marked *

*