我尝试直接在工人中导入猫鼬模型,例如:
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()
吗?