wilk / microjob

A tiny wrapper for turning Node.js worker threads into easy-to-use routines for heavy CPU loads.
https://wilk.github.io/microjob/
MIT License
2.02k stars 47 forks source link

save data to mongoose #58

Closed RezaErfani67 closed 4 years ago

RezaErfani67 commented 4 years ago
global.config=require('./config.js')
const mongoose = require('mongoose');
mongoose.Promise = global.Promise;
mongoose.connect(config.database.url , { useNewUrlParser: true });

(async () => {
    const { start, job } = require("microjob");

    try {
        // start worker pool
        await start();

        // this function will be executed in another thread
        const res = await job(async () => {
            let i = 0;
            console.log(1);
            let User = require('./model/user');
            console.log(2);
            let newuser=new User({nickName:"salam"});
            console.log(3);
            await newuser.save();
            console.log(4); //------------------------------ NOT SHOW---------------------------------------------

            return i;
        });

        console.log(res); // 1000000
    } catch (err) {
        console.error(err);
    }
})();
wilk commented 4 years ago

Do you have any error? What's the final output?

RezaErfani67 commented 4 years ago

it should add a record on database... but no thing happen... output is: 1 2 3

wilk commented 4 years ago

I'm thinking about your connection. Spawning a new thread requires a new connection to MongoDB. Have you tried adding the connection to the job?

const res = await job(async () => {
  global.config=require('./config.js')
  const mongoose = require('mongoose');
  mongoose.Promise = global.Promise;
  mongoose.connect(config.database.url , { useNewUrlParser: true });
  let i = 0;
  console.log(1);
  let User = require('./model/user');
  console.log(2);
  let newuser=new User({nickName:"salam"});
  console.log(3);
   await newuser.save();
   console.log(4); //------------------------------ NOT SHOW---------------------------------------------

   return i;
});
RezaErfani67 commented 4 years ago

yes....thanks a lot