带有MongoDB JSONFormat问题的NodeJS [英] NodeJS with mongoDB JSONFormat issue

查看:95
本文介绍了带有MongoDB JSONFormat问题的NodeJS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是NodeJS和MongoDb的新手.我在jsonObject上遇到问题.

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

步骤1:我已经在Ubuntu 16.04系统中成功安装了NodeJS和MongoDB.

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

步骤2:我在项目文件夹中使用package.json文件创建了所有服务器设置.

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

第3步:我创建了server.js文件,如下所示.

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

server.js 文件

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

然后我通过nodemon server.js运行节点服务器 服务器成功运行. 然后,我尝试使用POST MAN Application从数据库中获取数据.

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 方法:localhost:3000/tasks

GET method: localhost:3000/tasks

成功运行并产生结果.

如下所示,

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

我的问题在这里

1)我没有在此处创建 __ v id 字段.那为什么会来呢? 2)然后我需要在 Created_date 字段中使用正确的日期格式.例如"dd-MM-yyyy hh:mm".怎么做?

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.

更新

当我尝试安装时,会发生以下错误

When i try to install moment, following error occurs

notsup跳过依赖项:fsevents@1.1.1不受支持的平台:wanted {"os":"darwin","arch":"any"}(当前:{"os":"linux","arch" :"x64"})

notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.1.1: wanted {"os":"darwin","arch":"any"} (current: {"os":"linux","arch":"x64"})

推荐答案

1.  "_id": "58ba4c9c03e10b16d140775f"

这是mongodb为您插入的每个文档默认创建的唯一ID,mongo将创建一个_id,默认情况下将其设置为索引键.

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.

有关更多参考,您可以阅读 _id的优点

For more reference you can read advantage of _id

2."__v": 0

versionKey是Mongoose首次创建时在每个文档上设置的属性.此键值包含文档的内部修订版. versionKey选项是一个字符串,表示用于版本控制的路径.

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.

打开它以获取更多详细信息

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

是mongodb保存日期的默认格式.Mongodb使用ISO格式存储日期.如果要以这种方式保存,则可以以字符串格式存储日期,或者可以以ISO格式保存日期,但是在获取文档时,可以使用诸如时刻以您想要的格式显示日期.

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.

这篇关于带有MongoDB JSONFormat问题的NodeJS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆