Mongoose - 将json对象映射到Schema

时间:2017-04-20 11:08:26

标签: node.js mongodb mongoose mongoose-schema

我试图学习mongo / mongoose并将json导入mongodb。

我的json包含许多形式的对象:

{
   "FIELD1": "28/02/2017",
   "FIELD2": "string value",
   "FIELD3": "100"
 },
 {
   "FIELD1": "28/02/2017",
   "FIELD2": "string",
   "FIELD3": "57"
 },

我有一个架构:

var statementSchema = new Schema({
   //date: {type:Date, required: true},
   //name : {type:String, required:true},
   //amount: {type: Number, required:true}
   FIELD1 : {type:String, required:true},
   FIELD2: {type:String, required:true},
   FIELD3: {type:String, required:true}
});

你可以看到我真的希望db中的键能够更好地描述它们包含的值,而不是源json中的值(即我希望json中的FIELD1为{{1在DB)。

最好的方法是什么?我见过mongoose-aliasfield,这是最好的方法还是有一种默认方式在Schema中定义FIELD1 date someothername?

虽然我有你,但是将FIELD1和FIELD3分别从它们在json源中的当前String中转换为asDate的正确方法是什么? ;)

2 个答案:

答案 0 :(得分:0)

尝试使用这种方式。,ref Mongoose schema data type

<强>架构:

var statementSchema = new Schema({
   FIELD1 : {type:Date, required:true},
   FIELD2: {type:String, required:true},
   FIELD3: {type:Number, required:true}
});

插入

db.getCollection('users').save({
   "FIELD1": Date("28/02/2017"),
   "FIELD2": String("string"),
   "FIELD3": Number("57")
 })

<强>结果:

{
    "_id" : ObjectId("58f8ba663749f1f13fee40d6"),
    "FIELD1" : "Thu Apr 20 2017 19:10:54 GMT+0530 (IST)",
    "FIELD2" : "string",
    "FIELD3" : 57.0
}

答案 1 :(得分:0)

好的,这就是我真的是个新手。

现在定义了模式:

var statementSchema = new Schema({
date : {type:Date, required:true},
name: {type:String, required:true},
amount: {type:Number, required:true}
});

我插入使用:

var statements= require('../data/convertcsv.json');
var Statement = require('../models/statement');
var mongoose = require('mongoose');
mongoose.connect('localhost:27017/statement');

var parseDate = require('../helpers/parseDate');


var done = 0;
for( var i = 0; i < statements.length; i++ ) {
var newStatement = new Statement();
//helper function breaks string apart, reassembles and returns a Date
newStatement.date = parseDate.stringToDate(statements[i].FIELD1);
newStatement.name = statements[i].FIELD2;
newStatement.amount = Number(statements[i].FIELD3);

newStatement.save(function(err, result){
    done++;
    if(done === statements.length){
        exit();
    }
});

}

function exit(){
mongoose.disconnect();
};