Scope Issue w/ NPM?


#1

I’m having an issue right now that I believe is to do with scope, I’m sure an easy fix, but haven’t been able to find a way around it.

Using Meteor 1.3 btw…

I basically need an item to be inserted to database via results of a NPM function.

What’s happening is my function works completely fine server side, but from inside the NPM modules code, it seems Meteor’s insert functions are not working correctly from inside the NPM module. Also, errors are not showing up at all, so it’s been very hard to debug.

As an example, if I make a server side function of:

Test_Insert= function(subject, header, body) {
    console.log("Subject: " + subject);
    console.log("Header: " + header);
    console.log("Body: " + body);

    var attributes = {
        subject: subject,
        headers: header,
        body: body
    };
    TempCollection.insert(attributes);
};

Running Test_Insert from anywhere works completely fine inside most functions, just not inside of the NPM’s functionality. If I call from inside the NPM functions, I get the console, so variables are being passed…, but no insert, no error, no anything…

I tried setting a variable to “this” and calling it that way, no dice… I tried calling it through Mongo import but no dice either…

And this is asynchronous, so I can’t just insert it outside of the scope of the NPM module… Have to call it from inside.

Any advice please? As I said , I’m sure an easy fix, but I’ve had no luck so far…


#2

Without seeing more of your code, I suspect the issue is to do with Meteor’s sync-style MongoDB methods. These use fibers/futures and the fiber context is most likely lost. You could try running in a fiber of your own, or alternatively use the async method calls, which don’t use fibers:

TempCollection.insert(attributes, (error, result) => {
  // do stuff here
});

Alternatively, alternatively :wink:, you could wrap the async methods in Promises and do sync-style stuff with await inside an async function.