由于某种原因,我无法使用以下命令来工作,无法使用node.js驱动程序从mongodb数据库返回查询的文档。
function findSomething(){
const database = "learning";
const collection = "stuff";
var str;
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db(database);
dbo.collection(collection).findOne({}, function(err, result) {
if (err) throw err;
str = result.name;
db.close();
});
});
return str;
}
console.log(findSomething());
此输出
undefined
但是,如果我修改上面的代码以包含以下内容
console.log(str);
紧接着
str = result.name;
它将产生以下输出:
undefined
Company Inc //sample data from my document
我不明白的两件事是;
我知道我的第二个担心会回答我的第一个问题,我正在尝试这样做,因此我可以对mongodb crud函数进行模块化,以便使我的Express应用程序中的所有内容都更加简洁。
您是否在寻找类似下面的代码:
const express = require('express');
const MongoClient = require('mongodb').MongoClient;
const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
class MongoDB {
async connection(connection, options = {}) {
try {
const client = await MongoClient.connect(connection.URI, options);
const db = await client.db(connection.DB);
MongoDB.db = db;
MongoDB.client = client;
} catch(ex) {
console.log(ex.message);
}
}
}
MongoDB.db = {};
MongoDB.client = {};
class MongoModel extends MongoDB {
constructor(collectionName) {
super();
this.collectionName = collectionName;
}
get collection() {
return MongoModel.db.collection(this.collectionName)
}
}
// get mongodb, for an example: import from another file
const mongodb = new MongoDB();
// connect to mongodb from 'server.js' or 'app.js'
mongodb.connection({ URI: 'mongodb://localhost:27017', DB: 'blog_dev'}, { useUnifiedTopology: true });
const somethingModel = new MongoModel('something');
// an example another collection
const anotherModel = new MongoModel('anotherCollection');
// model find
async function findSomething() {
try {
const result = await somethingModel.collection.find({}).toArray();
return result;
} catch(ex) {
console.log(ex.message);
}
}
// model create
async function createSomething(payload) {
try {
const result = await somethingModel.collection.insert(payload);
return result.ops[0];
} catch(ex) {
console.log(ex.message);
}
}
// get controller
app.get('/', async (req, res) => {
try {
const result = await findSomething();
console.log(result);
res.status(200).send(result);
} catch(ex) {
console.log(ex.message);
}
});
// create controller
app.post('/', async(req, res) => {
try {
const result = await createSomething(req.body);
res.status(200).send(result);
} catch(ex) {
console.log(ex.message);
}
})
app.listen(3000, () => console.log('Server is up on port 3000'));
[有一个使用mongodb的简单
express
服务器示例。对于Advance MongoModel,您可以在node-modules
中安装并学习该代码。
我希望它可以帮助您获得新的想法。