如何在Node js中获得回调函数值

问题描述 投票:0回答:1

我是Node js和学习的新手。我被此代码所困扰,需要一个解决方案。

我的问题:我想获取此功能之外的所有找到的记录。我放入doc,以收集这些值并返回到函数。但这是不确定的。请让我知道如何解决此问题,并且也想知道调用此方法所用的术语是什么,以便我可以学习更多有关此类代码的信息

我的代码:

module.exports.getName=function findDocuments(db,toSearch) {
  // Get the documents collection
  const collection = db.collection('Product');
 var doc="hello world";
  console.log(toSearch+" valeu of seahcs");
  // Find some documents
  const name =collection.find({ '$text': 
                      {
                        '$search' : toSearch 
                      } 
                  } ).toArray(function(err, docs) {
    assert.equal(err, null);
    console.log("Found the following records  " +docs[0].ProductName);
    console.log(docs);
    doc=docs[0].ProductName// Need to get this value outside of findDocuments FUNCTION
    console.log(doc+"     doc value ");
    //return doc;
  });

  //var myJSON = JSON.stringify(collection);
//  console.log(collection +"   collection " + myJSON);
   console.log(doc+" doc 1 value ");
    return doc;

};


// use the findDocuments() function
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');

// Connection URL
const url = 'mongodb://localhost:27017';

// Database Name
const dbName = 'ng8crud';

const client = new MongoClient(url);

// Use connect method to connect to the Server
client.connect(function(err, client) {
  assert.equal(null, err);
  console.log("Connected correctly to server");

  const db = client.db(dbName);

  exports.dbname=db;


 /*  findDocuments(db, function() {
    client.close();
  }); */
});
javascript node.js callback
1个回答
0
投票
//dbConnection.js
const mongoClient = require('mongodb').MongoClient;
const mongoOptions = {};
const mongoUrl = process.env.MONGO_URL || "mongodb://localhost:27017/some-app";

function callback(err, r){
  debug("callback: ", err, r);
};

module.exports = function () {
  mongoClient.connect(mongoUrl, mongoOptions, (err, client) => {
    if(err){
      debug("MongoDB connection error: ", err);
      throw err;
    };
    const db = global.db = client.db();
    db.collection('users').createIndex({email: 1}, {unique: true}, callback);
    debug("Connected to mongoDB");
  });
};

//usage.js
require("./dbConnection")();
const db = global.db.collection("Product");
db.find({}).toArray(function(err, products){
  //do something with product data here

});
© www.soinside.com 2019 - 2024. All rights reserved.