How to fetch the details from mongo db and send or store in object in nodejs Fork method

这一生的挚爱 提交于 2019-12-03 18:16:10

问题


Here I am using fork method to do some calculation in node js. I have followed by the answer in link.It worked as expected and had started to do calculation.

Here how can I get the details from the mongodb in child file.I am using mongoose for mongodb. My sample code is below

main.js

    var childprocess = require('child_process');
    var child = childprocess .fork(__dirname + '/childpage');
    child.on('message', function(m) {
   // Receive results from child process
    console.log('received: ' + m);
   });

childpage

   var User = require('../models/User');   //mongoose schema
   var users= {};
   User.find({}, function (err, docs) {
    debugger;
   users = docs;          
   //process.send(users );               //Changed as in edit
    });

Here I am not getting any results in console. Can any one help me to get the details in child page from mongoDB and store it in one object. send those to mainjs to show in console

EDIT I have changed the process.send line to process.on method then it receiving in console but as a object.Even I tried with JSON.stringify(docs); also but same result.

 process.on('message', function(m) {
      process.send(users);
     });

IN Console

received: [object object]

Mongoose Schema

const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({
    FirstName: String,
    LastName: String,
    Email: { type: String, unique: true }   

}, { versionKey: false });

回答1:


This code snippet works perfectly for me. Please try this:

In main.js

var childprocess = require('child_process');
var child = childprocess.fork(__dirname + '/child');
child.on('message', function(m) {
    // Receive results from child process
    console.log('received: ',  m);
});

In child.js

var User = require('../models/User'); 
var users= {};
User.find({}, function (err, docs) {
    // Please add log in this line to check whether their is anything in database
    console.log(docs);
    debugger;
    users = docs;          
    process.send(users);              
});

For me this results:



来源:https://stackoverflow.com/questions/43490211/how-to-fetch-the-details-from-mongo-db-and-send-or-store-in-object-in-nodejs-for

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!