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:

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:

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:

{
  "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": "grokonez.com",
  "license": "ISC",
  "dependencies": {
    "express": "^4.16.4",
    "mongoose": "^5.4.2"
  }
}
Setting up Mongoose connection

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

module.exports = {
    url: 'mongodb://localhost:27017/nodejs-demo'
}
Create 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); 
Express RestAPIs
Route

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

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);
}
Controller

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

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
        });
    });
};
Server.js

server.js file:

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"	
	});
}
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 *

*