0
var mongoose = require('mongoose');
var Schema = mongoose.Schema;


const NewsAPI = require('newsapi');
const { response } = require('express');
const newsapi = new NewsAPI();

var current_date = new Date(Date.now());
var old_date = new Date(Date.now() - 864e5 - 864e5);

var current_date2 = JSON.stringify(current_date);
var old_date2 = JSON.stringify(old_date);

var today = current_date2.slice(1,11);
var day_b4_yesterday = old_date2.slice(1,11);

var feed;
newsapi.v2.everything({
    q: 'food and beverage',
    sources: '',
    domains: '',
    from: day_b4_yesterday,
    to: today,
    language: 'en',
    sortBy: 'relevancy',
    page: 2
}).then(response => {
    console.log(response);
    feed = response;

    

});


var NewsSchema = new Schema(feed);
module.exports = mongoose.model('News', NewsSchema);

I need to assign the response which is a JSON object created by the newsapi to a global variable to use it in the new Schema. How do I do that? As of now I'm not able to access it globally.

I have changed my code as follows and now it I'm able to access it but now I'm getting a Schema configuration error.

var mongoose = require('mongoose');
var Schema = mongoose.Schema;


const NewsAPI = require('newsapi');
const { response } = require('express');
const newsapi = new NewsAPI('87ca7d4d4f92458a8d8e1a5dcee3f590');

var current_date = new Date(Date.now());
var old_date = new Date(Date.now() - 864e5 - 864e5);

var current_date2 = JSON.stringify(current_date);
var old_date2 = JSON.stringify(old_date);

var today = current_date2.slice(1,11);
var day_b4_yesterday = old_date2.slice(1,11);


NewsLibrary = function(correct){
    var promise = new Promise(function(resolve, reject){
        if (correct){
            newsapi.v2.everything({
                q: 'food and beverage',
                sources: '',
                domains: '',
                from: day_b4_yesterday,
                to: today,
                language: 'en',
                sortBy: 'relevancy',
                page: 2
            }).then(response => {
                resolve(response);
            })
        }else{
            reject(new Error("Error loading news"))
        }
        

    });

    return promise;
}

NewsLibrary(true).then(function(response){
    console.log(response);
    var NewsSchema = new Schema(response);
    module.exports = mongoose.model('News', NewsSchema);
}).catch(function(err){
    console.log(err)
});

  • Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Kunal Mukherjee Jul 25 '20 at 15:33

3 Answers3

1

You have taken a global variable feed. But you are storing the response in window.feed. So you should store it in feed variable in the then block, That is the first thing.

Umar Awan
  • 86
  • 8
0

You can assign it by using global or GLOBAL, nodejs supports both:

global.feed = response;

or

GLOBAL.feed = response;

White Link
  • 106
  • 7
0

I think the main problem is because the method is asynchronous.

var NewsSchema = new Schema(feed);

This code should only work after the request is complete. But I think it would run before the request is complete because it is given outside the promise (the then statement).

Ideally you should return a promise from this method or a function which will return the correct value and handle the promise in the module which imports this. An example would be,


var model = newsapi.v2.everything({
    q: 'food and beverage',
    sources: '',
    domains: '',
    from: day_b4_yesterday,
    to: today,
    language: 'en',
    sortBy: 'relevancy',
    page: 2
}).then(response => {
    console.log(response);
    var NewsSchema = new Schema(response);
    return mongoose.model('News', NewsSchema);
});


module.exports = { model };

You can handle the resolution of this promise in the file or method which requires this. If interested in more asynchronous code look here at MDN web docs,

  • I tried this example but it throws an error stating Schema hasn't been registered for model "News". – Kritartha Borthakur Jul 25 '20 at 16:21
  • I had made an error in the previous code has corrected it please try again. Remember that requiring this file will return a promise – boredfromboredom Jul 25 '20 at 16:34
  • I actually tried something similar to what you suggested what it's the same error. – Kritartha Borthakur Jul 25 '20 at 17:29
  • `var NewsSchema = newsapi.v2.everything({ q: 'food and beverage', sources: '', domains: '', from: day_b4_yesterday, to: today, language: 'en', sortBy: 'relevancy', page: 2 }).then(response => { console.log(response); return mongoose.model('News', new Schema(response)); }); module.exports = {NewsSchema} ;` – Kritartha Borthakur Jul 25 '20 at 17:31
  • I have not worked that much with mongoose. But doesn't it need to define the Schema before hand. If you need to inert without knowing about the schema try https://stackoverflow.com/questions/5370846/how-do-you-use-mongoose-without-defining-a-schema. But in most cases you need to know about the schema if the data. – boredfromboredom Jul 26 '20 at 02:44