1
votes

Trying to create a new entry in the DB, but I keep getting an error about my code not being in a fiber. I have no idea what the problem could be. I must add that I am doing the insert on the server side. This is not a Method call from a client.

Here is my code.

import {Meteor} from 'meteor/meteor';
import {Mongo} from 'meteor/mongo';
import SimpleSchema from 'simpl-schema';





export const Trxs = new Mongo.Collection('trx');

export const addTrx = (trxn, userId) => {

    var date = new Date(trxn.date).valueOf();
    var userId = userId;
    var catID = trxn.category_id;
    var amt = trxn.amount;
    var trx_name = trxn.name;

    console.log(trxn);

    Trxs.insert({
        date,
        userId,
        catID,
        amt,
        trx_name
    });
}

And this is the error I am getting.

Error: Meteor code must always run within a Fiber. Try wrapping callbacks that you pass to non-Meteor libraries with Meteor.bindEnvironment.

1
Have you tried it without an arrow function? Because Fibers work with a particular context, it might not work in an arrow function...?coagmano
Still getting the same issue without an arrow function.Justin A
Meteor.bindEnvironment should do the trickJankapunkt
Put everthing in Meteor.method then call method from anywhere.. console/shell, client or server.Abhishek Maurya
If you must work outside a Meteor method and you have to make a call to a Mongo Collection (for example you write a package that includes common code) you will need to wrap the method using bindEnvironment.Jankapunkt

1 Answers

1
votes

If your function is used as callback or is called within a callback on the server, then it looses the Meteor environment's context.

This is often the case when dealing with async functions on the server. The error above occurs, because there is also a call Mongo.Collection methods (which are not raw Mongo calls but have been rewritten according to the Meteor environment).

You need to wrap it therefore by using Meteor.bindEnvironment. You can reproduce this easily:

trx.js

import {Mongo} from 'meteor/mongo';

export const Trxs = new Mongo.Collection('trx');

export const addTrx = Meteor.bindEnvironment((trxn, userId) => {

    var date = new Date(trxn.date).valueOf();
    var userId = userId;
    var catID = trxn.category_id;
    var amt = trxn.amount;
    var trx_name = trxn.name;

    Trxs.insert({
        date,
        userId,
        catID,
        amt,
        trx_name
    });
});

main.js

import {addTrx, Trxs} from "./modc";


setTimeout(function () {
    console.log("call")
    addTrx({
        category_id: "12312321",
        amount: 10000,
        name: "foo",
    }, '123123123')
}, 5000);

If you would remove the bindEnvironment wrapping of the function, the code in main.js will throw the same Error, that you received.

Resources for further reading:

https://guide.meteor.com/using-npm-packages.html#bind-environment

https://docs.meteor.com/api/collections.html#Mongo-Collection