Reputation: 143
What I want to do is to create my DataBase from an external API, firstly I create a function loadData(req, res){}
in my DBController, this function loads the data in JSON format from the API.
What I want to do now is to save this returned JSON within my mongoDB, I don't know how. How can I do that please?
Upvotes: 1
Views: 1048
Reputation: 111
npm install sails-mongo --save
Define a connection in config/connections.js. You can make it a default connection under config/models.js if you are not using other database.
Then, you would have to create a Model with definitions similar to the content of the JSON that the external API is returning.
For eg. if the external API is returning.
[{
attribute1: '<value>',
attribute2: '<value>',
attribute3: '<value>'
}]
You would want to create a Model under /api/models called Model.js like below,
module.exports = {
attributes: {
attribute1: {type: 'integer'},
attribute2: {type: 'string'},
attribute3: {type: 'datetime'}
}
};
Refer to this to get more idea on creating a model.
Then in your controller you can just do,
var externalJSON = <API result JSON>;
Model.create(externalJSON)
.exec(function(err, user){
//Processing
});
Upvotes: 2
Reputation: 5979
If the JSON represents an array of records that match the structure of your db, then all you need to do is load the file and save the contents
var data = require('./datafile.json')
MODEL.create(data).exec(function(err,result){/*...*/})
Upvotes: 2