0

我尝试直接在工人中导入猫鼬模型,例如:

  Worker, isMainThread, parentPort, workerData
} = require('worker_threads');

if (isMainThread) {
  module.exports = function parseJSAsync(script) {
    return new Promise((resolve, reject) => {
      const worker = new Worker(__filename, {
        workerData: null
      });
      worker.on('message', resolve);
      worker.on('error', reject);
      worker.on('exit', (code) => {
        if (code !== 0)
          reject(new Error(`Worker stopped with exit code ${code}`));
      });
    });
  };
} else {
  const MyModel = require("../models/MyModel.js");
  const data = await MyModel.find();
}

查询未运行!但没有异常或错误

因此,我尝试从主线程将模型作为 WorkerData 传递:

const {
  Worker, isMainThread, parentPort, workerData
} = require('worker_threads');

const MyModel = require("../models/MyModel.js");

if (isMainThread) {
  module.exports = function parseJSAsync(script) {
    return new Promise((resolve, reject) => {
      const worker = new Worker(__filename, {
        workerData: MyModel
      });
      worker.on('message', resolve);
      worker.on('error', reject);
      worker.on('exit', (code) => {
        if (code !== 0)
          reject(new Error(`Worker stopped with exit code ${code}`));
      });
    });
  };
} else {
  
  const MyModel = workerData;
  const data = await MyModel.find();
}

这次我得到了例外:

DOMException [DataCloneError]: function model(doc, fields, skipId) {
      model.hooks.execPreSync('createModel', doc);
      if (!(this insta...<omitted>... } could not be cloned.
    at new Worker (internal/worker.js:144:17)

我该怎么做才能从 Worker 线程访问数据库?

我应该使用 : 在线程中建立与数据库的单独连接 mongoose.connect()吗?

4

1 回答 1

0

我不知道你是否解决了你的问题,但我也有同样的情况,对于到达这里的人来说,解决方案是:事实上(就像@jackOfAll 假设的那样):建立与 DB 的连接

于 2020-08-29T23:17:17.797 回答