Michael
Michael

Reputation: 16122

From .json file to mongoose schema?

I have a .json file that includes dictionaries(objects) and arrays.

Before, front-end just asked the the server for this .json file. But now I have added a mongo database. And I figured that it would be better to hold and send this data from mongo.

So I need to write a small program that would open my .json file, read it and store this data in mongoose schema.

What is the propitiate way to do it?

Upvotes: 1

Views: 1749

Answers (1)

ATC
ATC

Reputation: 176

You could just store the JSON directly, but if it's a static file and you don't expect loads of them, then you're likely just introducing more work for yourself by setting up a DB.

However, if you really want to do it that way, this is the quick-messy-and-not-production-worthy way of doing that.

var schema = mongoose.Schema({key : JSON}),
    Json = mongoose.model('JSON', schema),
    toSave = new Json({key : yourJsonObject});

toSave.save(function(err){
   'use strict';
   if (err) {
       throw err;
   }
   console.log('woo!');
})

Upvotes: 2

Related Questions