繁体   English   中英

MongoDB和node.js存储自定义JSON

[英]MongoDB and node.js store custom JSON [closed]

我正在构建一个API,该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",
}]

您不能在MongoDB本身中定义json结构。 MongoDB按照给定的json文档进行操作。 您可能可以使用ORM定义文档结构。

当我看到你有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 },

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM