1

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?

2 Answers 2

2
  1. Make sure you have sails-mongo adapters added in the module otherwise use, npm install sails-mongo --save
  2. 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.

  3. 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.

  1. Then in your controller you can just do,

    var externalJSON = <API result JSON>;
    Model.create(externalJSON)
    .exec(function(err, user){ 
       //Processing 
    });
    
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, the externalJSON contains some attributes that I wont use in my DB, e.g if I create a model with juste attribute1&2, Will my model be creatd even if it dosen't match externalJSON ?
you can just remove the unwanted attributes from externalJSON before Mode.create. Try lodash for arrays. Read basics of Models here : sailsjs.org/#!/documentation/concepts/ORM/Models.html
2

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){/*...*/})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.