Reputation: 987
I'm trying to learn mongo/mongoose and am importing json into mongodb.
My json contains a number of objects of the form:
{
"FIELD1": "28/02/2017",
"FIELD2": "string value",
"FIELD3": "100"
},
{
"FIELD1": "28/02/2017",
"FIELD2": "string",
"FIELD3": "57"
},
I have a schema:
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}
});
You can see that I would really like the keys in the db to be more descriptive of the values they contain than they are in the source json (i.e. I would prefer FIELD1
in the json to be date
in the DB).
What is the best way to do this? I have seen mongoose-aliasfield, is that the best approach or is there a default way to define FIELD1 as
someothername in the Schema?
While I have you, what's the correct way to cast FIELD1 and FIELD3 as Date
and Number
respectively from their current String in the json source? ;)
Upvotes: 0
Views: 3331
Reputation: 987
OK so this was me being a newb really.
Schema is now defined:
var statementSchema = new Schema({
date : {type:Date, required:true},
name: {type:String, required:true},
amount: {type:Number, required:true}
});
and I insert using:
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();
};
Upvotes: 1
Reputation: 20158
try to use this way., ref Mongoose schema data type.
schema:
var statementSchema = new Schema({
FIELD1 : {type:Date, required:true},
FIELD2: {type:String, required:true},
FIELD3: {type:Number, required:true}
});
Insert:
db.getCollection('users').save({
"FIELD1": Date("28/02/2017"),
"FIELD2": String("string"),
"FIELD3": Number("57")
})
result:
{
"_id" : ObjectId("58f8ba663749f1f13fee40d6"),
"FIELD1" : "Thu Apr 20 2017 19:10:54 GMT+0530 (IST)",
"FIELD2" : "string",
"FIELD3" : 57.0
}
Upvotes: 0