首页 > 解决方案 > 为什么当我使用 nodejs child_processes fork 功能时,猫鼬保存功能不起作用

问题描述

首先,我有没有 child_proces 和 mongo db 的 nodejs 项目。它确实有效,我获取数据并插入 mongo db。

我的架构

const mongoose = require('mongoose');

var Schema = mongoose.Schema;

var TestSchema = new Schema({
  ID:String,
  username:String,
  full_name:String
});
module.exports = mongoose.model('Test',TestSchema);

插入数据

let testInsert = {
    ID:1,
    username:'test_user',
    full_name:'test_full'
};

let test = new Test(testInsert);

test.save(err => {
    if(err){
        console.log(err);
    } else{
        console.log('insert')

    }
});

它确实有效,但是当我使用 child_process test.save 时不起作用,甚至无法进入。

标签: node.jsmongodbmongoosechild-process

解决方案


在没有看到任何其他代码的情况下,我只能假设问题是该过程在 MongoDB 之前完成。尝试更改您的代码以等待save完成,例如

(async () => {
  try {
    const test = new Test({
      ID:1,
      username:'test_user',
      full_name:'test_full'
    });
    await test.save();
  } catch (e) {
    console.error(e);
  }
})()

推荐阅读