I am trying to post the data to the database .then query the database for the last 3 entries .then res.send all of the data to ajax/console.log.
However If I empty the database collection on my first button click, it will grab and post the data to mongodb collections, however res.send will send an empty json array before its finished so the consolelog is empty and the html display is blank.
(Note: I did check after first button press to make sure there was data inside: I'm figuring that it's probably not grabbing the latest of existing data, not the ones that were just pushed into the collection database ex id3-6 instead of id7-9, I'm uploading news articles 3 at a time, so when I test the titles are duplicates every time.
When I click it a second time, it has data waiting already in the database so, it will load up and display data then, but unsure why the promise is not working. Also the resolve is working.
const express = require('express');
const {grabArticles} = require('../controller/scrapper.js');
const Article = require('../models/articles');
const Current = require('../models/current');
const mongoose = require('mongoose');
mongoose.Promise = global.Promise;
// const Comments = require('../models/comments');
// variables
const router = express.Router();
router.get('/api/fetch', (err, res) => {
const promiseInfo = new Promise((resolve, reject) => {
if ( grabArticles() === undefined ) {
console.log('hurrayyyy');
resolve();
} else {
console.log('oh nooooooo!');
reject();
}
});
promiseInfo.then(() => {
Current.find({}, 'topic title', (err, data) => {
}).limit(3)
// gives the last three articles saved in current models
.sort({createdAt: 'desc'})
.then((data) => {
res.send({response: data, total: 'Articles were found!'});
// console.log(data);
})
});
});