【问题标题】:MongoDB and node.js store custom JSON [closed]MongoDB 和 node.js 存储自定义 JSON [关闭]
【发布时间】:2014-01-24 06:31:53
【问题描述】:

我正在构建一个 API,它需要使用特定的“json”结构进行响应,该结构看起来与来自其他 API 的响应完全一样。

我的问题是如何将其存储在 MongoDB 中,并最终使用此自定义 json 文档进行回放。

我需要让响应看起来完全像这样:

[{
    "number": "510616221626",
    "date": "2013-12-02T00:00:00+01:00",
    "groupType": "D",
    "type": "I",
    "amount": "35200"
}, {
    "number": "510447942721",
    "date": "2013-11-02T00:00:00+01:00",
    "groupType": "D",
    "type": "I",
    "amount": "35100",
}, {
    "number": "509469895726",
    "date": "2013-05-02T00:00:00+02:00",
    "groupType": "D",
    "type": "I",
    "amount": "41700",
}]

【问题讨论】:

    标签: json node.js mongodb mongoose


    【解决方案1】:

    您不能在 MongoDB 本身中定义 json 结构。 MongoDB 将 json 文档作为给定的。您可以使用 ORM 定义文档结构。

    【讨论】:

      【解决方案2】:

      我看到你的标签中有mongoose,这是我对mongoose的测试:

      var mongoose = require('mongoose');
      mongoose.connect('localhost', 'test');
      
      var myJson = [{
          "number": "510616221626",
          "date": "2013-12-02T00:00:00+01:00",
          "groupType": "D",
          "type": "I",
          "amount": "35200"
      }, {
          "number": "510447942721",
          "date": "2013-11-02T00:00:00+01:00",
          "groupType": "D",
          "type": "I",
          "amount": "35100",
      }];
      
      var MySchema = mongoose.Schema({
          // use select: false to remove these default fields
          _id: {type: mongoose.Schema.ObjectId, auto: true, select: false},
          __v: {type: Number, select: false},
      
          number: { type: String, unique: true },
          date: Date,
          groupType: String,
          type: String,
          amount: Number
      });
      
      MyModel = mongoose.model('MyModel', MySchema);
      
      // create or save to collection
      MyModel.create(myJson, callback);
      
      // then find then stringify then print
      function callback(err, docs) {
      
          MyModel.find({}).exec(function (err, docs) {
                  console.log(JSON.stringify(docs, null, 2));
          });
      }
      

      输出字符串:

      [
        {
          "number": "510616221626",
          "date": "2013-12-01T23:00:00.000Z",
          "groupType": "D",
          "type": "I",
          "amount": 35200
        },
        {
          "number": "509469895726",
          "date": "2013-05-01T22:00:00.000Z",
          "groupType": "D",
          "type": "I",
          "amount": 41700
        }
      ]
      

      编辑:

      我忘记在架构中添加auto: true

      _id: {type: mongoose.Schema.ObjectId, auto: true, select: false },
      

      【讨论】:

      • 谢谢,我之前尝试过类似的方法,但没有成功。当我尝试上面的代码时,我只得到输出:[]
      • 我忘了'auto': true,所以mongo要求我们在创建文档之前添加_id
      猜你喜欢
      • 2016-06-25
      • 1970-01-01
      • 2018-04-02
      • 2010-11-29
      • 2011-10-20
      • 1970-01-01
      • 1970-01-01
      • 2015-08-17
      • 2017-03-03
      相关资源
      最近更新 更多