gpt4 book ai didi

javascript - 在 Node JS 中从 MongoDB 查询获取数据

转载 作者:行者123 更新时间:2023-12-03 02:46:30 25 4
gpt4 key购买 nike

我正在尝试从 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));
};

最佳答案

如果不重新调整整个代码,我无法为您提供一个好的答案。我已将应用程序的逻辑分离在不同的文件中

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('\n') // 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));

关于javascript - 在 Node JS 中从 MongoDB 查询获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48073251/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com