1

I am new to NodeJS and MongoDb. I am facing an issue on jsonObject.

Step 1: I have installed NodeJS and MongoDB sucessfully in my ubuntu 16.04 system.

Step 2: I created the all server setup with package.json file in my project folder.

Step 3: I created the server.js file Like below.

server.js File

    express = require('express'),
    routes = require('./api/routes/todoListRoutes');
    mongoose = require('mongoose'),
    Task = require('./api/models/todoListModels'),
    bodyParser = require('body-parser');
    app = express(),
    port = process.env.PORT || 3000,
    mongoose.Promise = global.Promise;
    mongoose.connect('mongodb://localhost/Tododb');
    app.use(bodyParser.urlencoded({ extended: true }));
    app.use(bodyParser.json());
    routes(app);
    app.listen(port);
    console.log('todo list RESTful API server started on: ' + port);

then I created Model file for storing the records.

todoListModels.js

    'use strict';
    var mongoose = require('mongoose');
    var Schema = mongoose.Schema;


    var TaskSchema = new Schema({
      name: {
        type: String,
        Required: 'Kindly enter the name of the task'
      },
      Created_date: {
        type: Date,
        default: Date.now
      },
      status: {
        type: [{
          type: String,
          enum: ['pending', 'ongoing', 'completed']
        }],
        default: ['pending']
      }
    },{ versionKey: false }//Updated);

    module.exports = mongoose.model('Tasks', TaskSchema);

todoListRoutes.js

'use strict';
module.exports = function(app) {
  var todoList = require('../controllers/todoListController');
  app.route('/tasks').get(todoList.list_all_tasks).post(todoList.create_a_task);
  app.route('/tasks/:taskId').get(todoList.read_a_task).put(todoList.update_a_task).delete(todoList.delete_a_task);
};

todoListController.js

'use strict';


mongoose = require('mongoose'),
Task = mongoose.model('Tasks');

exports.list_all_tasks = function(req, res) {
  Task.find({}, function(err, task) {
    if (err)
      res.send(err);
    res.json(task);
  });
};

exports.create_a_task = function(req, res) {
  var new_task = new Task(req.body);
  new_task.save(function(err, task) {
    if (err)
      res.send(err);
    res.json(task);
  });
};


exports.read_a_task = function(req, res) {
  Task.findById(req.params.taskId, function(err, task) {
    if (err)
      res.send(err);
    res.json(task);
  });
};


exports.update_a_task = function(req, res) {
  Task.findOneAndUpdate(req.params.taskId, req.body, {new: true}, function(err, task) {
    if (err)
      res.send(err);
    res.json(task);
  });
};


exports.delete_a_task = function(req, res) {
  Task.remove({
    _id: req.params.taskId
  }, function(err, task) {
    if (err)
      res.send(err);
    res.json({ message: 'Task successfully deleted' });
  });
};

Then i ran the node server by nodemon server.js Server successfully ran. then, I try to get the data from the database using POST MAN Application.

So, I did like below,

GET method: localhost:3000/tasks

it successfully ran and it produced result.

like below,

[
  {
  "_id": "58ba4c9c03e10b16d140775f",
   "name": "Karthik",
   "__v": 0,
   "status": [
   "pending"
  ],
  "Created_date": "2017-03-04T05:11:56.590Z"
}]

My problem is here,

1)I didn't created the __v and id fields here. Then why it is coming? 2)Then i need proper date format in Created_date field. like "dd-MM-yyyy hh:mm". How to do it?

Help will be appreciated.Thank you.

UPDATE

When i try to install moment, following error occurs

notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for [email protected]: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})

1 Answer 1

1
1.  "_id": "58ba4c9c03e10b16d140775f"

this is the by default unique id created by mongodb for every document that you insert mongo will create an _id which is by default set as an index key.

For more reference you can read advantage of _id

2."__v": 0

The versionKey is a property set on each document when first created by Mongoose. This keys value contains the internal revision of the document. The versionKey option is a string that represents the path to use for versioning.

open this for more details

3."Created_date": "2017-03-04T05:11:56.590Z"

Is the default format that mongodb Save date in. Mongodb Uses ISO format to store the date. If you want to save it that way you can store date in string format but or you can save in ISO format but when you are fetching the document you can use modules such as Moment to display the date in which ever format you want.

Sign up to request clarification or add additional context in comments.

9 Comments

How to get rid of __v from json.?How to set the proper date of mine?
you can add do this at the time of inserting the data. new Schema({..}, { skipVersioning: { dontVersionMe: true } }); thing.dontVersionMe.push('hey'); thing.save(); // version is not incremented
or if you want dont want to get it when you are using retrieving the data you can use this Models.facilities.find(criteria, {__v:0}, options, callback); pass __v:0 in projection.
moment not installing on ubuntu 16.04.
Yes that's correct just you need to close that square bracket as well. And you can install npm module of moment.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.