我是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();
}); */
});
答案 0 :(得分: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
});