Dragan
Dragan

Reputation: 1

Getting API Data and writing to MongoDB using NodeJS

Im learning NodeJS and trying to put up a mock website locally. Basically, its a website that uses the WOW AuctionHouse API. I take the data from the request, parse it to JSON and attempt to write it to the DB. The problem is, if i put the auctions.save inside the request it doesnt recognize the .save function as a function (assuming im out of the scope for it) and if i place it outside the problem comes from the async nature and i get an empty entry in my DB. Here is the code:

var express = require('express');
var hbs = require('express-hbs');
var mongoose = require('mongoose');
//var blizzard = require('blizzard.js').initialize({ apikey: "xxx" });

mongoose.connect('mongodb://127.0.0.1/blood_of_sargeras')

var post = mongoose.model(
  'post',
  {
    name: String,
    type: String,
    price: String
  });

var app = express();

app.engine('hbs', hbs.express4({
  partialsDir:__dirname+'/views/partials'
}));

app.set('view engine', 'hbs');
app.set('views', __dirname + '/views');

app.use('/static', express.static('static'));

var request = require("request");
var url = "http://auction-api-eu.worldofwarcraft.com/auction-data/xxx-xxx/auctions.json"
var auctions = new post;

request({
    url: url,
    json: true
}, function (error, response, body) {

    if (!error && response.statusCode === 200) {
        auctions = JSON.stringify(body);
        post.save(function (err) {
          if(err)
            console.log("Error with database!");
          else
            console.log("Data written to DB!");

        })
    }
});

app.get('/', function (req, res){

  post.find({}, function (err, o){
    if (err)
      console.log('Database  error!');
    else{
      res.render('index', o);
    }
  });
});

app.listen(80, function(){
  console.log('Listening on port 80')
});

Is this even the right way to do it? Is there a better way? I've been stuck on this for quite a while and its gotten extremely frustrating. Other things i tried are:

Upvotes: 0

Views: 1745

Answers (2)

Matt Kuhns
Matt Kuhns

Reputation: 1368

Try this:

var postSchema = mongoose.Schema({name: String,mType: String,price: String});
var post = mongoose.model('Post',postSchema);

var newPost = new Kitten();

Then later in request:

newPost.name = auctions.name;
newPost.mType = auctions.type;    //do not use type it is reserved
newPost.price = auctions.price

newPost.save(function(err, mPost) {
    if (err) console.error(err);
    console.log(mPost);
});

Upvotes: 0

Simon Mo
Simon Mo

Reputation: 773

I think you might need to wrap your request in an event listener. This will ensure the request runs once the server has finished starting up rather than before. Here is a quick example.

app.on('listening', function () {
    // Run your request to the WoW auction house  once the express server has started up
    request({
        url: url,
        json: true
    }, function (error, response, body) {

        if (!error && response.statusCode === 200) {
            auctions = JSON.stringify(body);
            post.save(function (err) {
                if(err)
                    console.log("Error with database!");
                else
                    console.log("Data written to DB!");

            })
        }
    });
});

Upvotes: 1

Related Questions