How to fetch the details from mongo db and send or

2019-01-29 07:09发布

问题:

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: