0

So I'm trying to learn a little NodeJS and working with mongoDB. It's been pretty fun so far but I'd need help with that next step: I'm trying to insertOne into the collection from an async function. Since the function is async it appears that the insert completes before the info it has to insert comes back.

Anyways, I'm trying to insert an object that I got from a function basically and can't seem to do it correctly, can anyone point me into the right direction?

Here's the github so that you can get the npm modules I'm using and here's the code:

var MongoClient = require('mongodb').MongoClient
  , assert = require('assert');

const KrakenClient = require('@warren-bank/node-kraken-api')
const kraken = new KrakenClient('api_key', 'api_secret', {timeout: 10000})


var url = 'mongodb://localhost:27017/mongoTuto';

MongoClient.connect(url, function(err, db) {
  assert.equal(null, err);
  console.log("Connected to the server.");
  insertDocuments(db, function() {
      db.close();
  });

});

var insertDocuments = function(db, callback) {

  var collection = db.collection('documents');

  collection.insertOne({
    ticker
  }, function(err, result) {
    assert.equal(err, null);
    console.log("Inserted documents into the collection");
    callback(result);
  });
}

var ticker = kraken.api('Ticker', {"pair": 'XXBTZEUR'})
                .then((result) => {
                  result
                })
                .catch((error) => {
                  console.log('Error:', error.message)
                });

Thanks in advance for your help and sorry for that very noobish question!

Martin Carre
  • 1,157
  • 4
  • 20
  • 42
  • 1
    You have it the wrong way around. You call the async API `kraken.api` within it's `.then()` you call your `insertOne`. Which funny enough also returns a "Promise" so basically `return` that and continue the promise chain. But basically directing you to what every "learning NodeJS" should be reading. – Neil Lunn Jul 23 '17 at 11:07
  • You're the best Neil! Thanks a lot for your answer and sorry for the duplicate (apparently)... – Martin Carre Jul 23 '17 at 13:58

0 Answers0