从Node JS中的MongoDB查询中获取数据
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了从Node JS中的MongoDB查询中获取数据相关的知识,希望对你有一定的参考价值。
我试图从find()方法获取数据,以使用find()方法之外的数据。我想在JSON响应中使用数据。这段代码效果不好。数据未在find()方法之外定义。如何在响应中使用数据?
var path = '';
var direct = '';
var MongoClient = require('mongodb').MongoClient;
var assert = require('assert');
var url = 'mongodb://localhost:27017/serverad';
MongoClient.connect(url,function(err,db){
assert.equal(err,null);
db.collection("adchar").find(
{ target_gender: 'female' },
{ad_path:1,ad_direct:1, _id:0}).toArray(function(err,docs){
callback(docs);
assert.equal(err,null);
path =docs[0].ad_path;
direct =docs[0].ad_direct;
});
});
exports.get = function(req, res) {
res.writeHead(200 , { 'content-Type':'application/json'})
var myObj = {
AdUrl:path
,dirURL : direct,
};
res.end(JSON.stringify(myObj));
};
答案
做这个工作人员。代码不完整
var path = '';
var direct = '';
var MongoClient = require('mongodb').MongoClient;
var assert = require('assert');
var url = 'mongodb://localhost:27017/serverad';
var fetchData = function(callback){
MongoClient.connect(url,function(err,db){
assert.equal(err,null);
db.collection("adchar").find(
{ target_gender: 'female' },
{ad_path:1,ad_direct:1, _id:0}).toArray(function(err,docs){
callback(err ,docs);
assert.equal(err,null);
path =docs[0].ad_path;
direct =docs[0].ad_direct;
});
});
};
exports.get = function(req, res) {
fetchData (function(error,result){
if(error){
// do error staff here
} else{
res.writeHead(200 , { 'content-Type':'application/json'})
var myObj = {
AdUrl:path
,dirURL : result,
};
res.end(JSON.stringify(myObj));
}
});
};
另一答案
如果不重新编写整个代码,我无法为您提供良好的答案。我在不同的文件中分离了应用程序的逻辑
db.js
const { MongoClient } = require('mongodb');
// these variables are not set until the connecion is established, any attempt
// to use them before that will, most likely, throw an error;
exports.client = undefined;
exports.database = undefined;
exports.adCharCollection = undefined;
exports.connect = async function connect(host, dbName) {
exports.client = await MongoClient.connect(host);
exports.database = exports.client.db(dbName);
exports.adCharCollection = exports.database.collection("adchar");
}
model.js
const db = require('./db');
exports.getResults = async function getResults(gender) {
const docs = db.adCharCollection
.find({ target_gender: gender }, { ad_path: 1, ad_direct: 1, _id: 0 })
.limit(1)
.toArray();
if (!docs.length) {
return null;
}
const doc = docs[0];
return { AdUrl: doc.ad_path, dirURL: doc.ad_direct };
}
controller.js
const { getResults } = require('./model');
exports.get = async function get(req, res) {
try {
const result = await getResults("female");
res.writeHead(200, { "content-Type": "application/json" });
res.end(JSON.stringify(result));
} catch (err) {
res.writeHead(500, { "content-Type": "application/json" });
res.end(JSON.stringify({
error: true,
message: err.message,
stack: err.stack.split('
') // the stack only for development purposes
}));
}
}
server.js
const http = require('http');
const { connect } = require('./db');
const { get } = require('./controller');
const PORT = 3000;
const MONGO_HOST = 'mongodb://localhost:27017';
const MONGO_DB = 'serverad';
async function main() {
// we first need to connect to mongo before doing anything
await connect(MONGO_HOST, MONGO_DB);
// set the request handler
const server = http.createServer(get);
await new Promise((resolve, reject) => {
server.listen(PORT, (err) => {
if (err) {
reject(err);
return;
}
console.log(`server running at http://localhost:${PORT}/`);
resolve();
});
});
return server;
}
main().catch(err => console.log(err.stack));
以上是关于从Node JS中的MongoDB查询中获取数据的主要内容,如果未能解决你的问题,请参考以下文章
使用 node.js 从 Mongodb 获取数据时,浏览器会一直加载