Thursday, 20 April 2017

Mongoose - mapping json object to Schema

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? ;)



via Stuart Brown

No comments:

Post a Comment