Javascript 如何在 Node.js 中使用带有承诺的 MongoDB?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37911838/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use MongoDB with promises in Node.js?
提问by user1620696
I've been trying to discover how to use MongoDB with Node.js and in the docs it seems the suggested way is to use callbacks. Now, I know that it is just a matter of preference, but I really prefer using promises.
我一直在尝试发现如何将 MongoDB 与 Node.js 一起使用,并且在文档中似乎建议的方法是使用回调。现在,我知道这只是一个偏好问题,但我真的更喜欢使用 Promise。
The problem is that I didn't find how to use them with MongoDB. Indeed, I've tried the following:
问题是我没有找到如何在 MongoDB 中使用它们。确实,我尝试了以下方法:
var MongoClient = require('mongodb').MongoClient;
var url = 'mongodb://localhost:27017/example';
MongoClient.connect(url).then(function (err, db) {
console.log(db);
});
And the result is undefined
. In that case it seems this is not the way to do so.
结果是undefined
。在那种情况下,这似乎不是这样做的方法。
Is there any way to use mongo db inside Node with promises instead of callbacks?
有什么方法可以在 Node 中使用 mongo db 和 promise 而不是回调吗?
回答by Green
Your approach is almost correct, just a tiny mistake in your argument
你的方法几乎是正确的,只是你的论点中的一个小错误
var MongoClient = require('mongodb').MongoClient
var url = 'mongodb://localhost:27017/example'
MongoClient.connect(url)
.then(function (db) { // <- db as first argument
console.log(db)
})
.catch(function (err) {})
回答by PirateApp
Since none of the answers above mention how to do this without bluebird or q or any other fancy library, let me add my 2 cents on this.
由于上面的答案都没有提到在没有 bluebird 或 q 或任何其他花哨的图书馆的情况下如何做到这一点,让我在这上面加上我的 2 美分。
Here's how you do an insert with native ES6 promises
以下是如何使用原生 ES6 承诺进行插入
'use strict';
const
constants = require('../core/constants'),
mongoClient = require('mongodb').MongoClient;
function open(){
// Connection URL. This is where your mongodb server is running.
let url = constants.MONGODB_URI;
return new Promise((resolve, reject)=>{
// Use connect method to connect to the Server
mongoClient.connect(url, (err, db) => {
if (err) {
reject(err);
} else {
resolve(db);
}
});
});
}
function close(db){
//Close connection
if(db){
db.close();
}
}
let db = {
open : open,
close: close
}
module.exports = db;
I defined my open() method as the one returning a promise. To perform an insert, here is my code snippet below
我将 open() 方法定义为返回承诺的方法。要执行插入,下面是我的代码片段
function insert(object){
let database = null;
zenodb.open()
.then((db)=>{
database = db;
return db.collection('users')
})
.then((users)=>{
return users.insert(object)
})
.then((result)=>{
console.log(result);
database.close();
})
.catch((err)=>{
console.error(err)
})
}
insert({name: 'Gary Oblanka', age: 22});
Hope that helps. If you have any suggestions to make this better, do let me know as I am willing to improve myself :)
希望有帮助。如果您有任何改进建议,请告诉我,因为我愿意改进自己:)
回答by ginad
You can also do async/await
你也可以做异步/等待
async function main(){
let client, db;
try{
client = await MongoClient.connect(mongoUrl, {useNewUrlParser: true});
db = client.db(dbName);
let dCollection = db.collection('collectionName');
let result = await dCollection.find();
// let result = await dCollection.countDocuments();
// your other codes ....
return result.toArray();
}
catch(err){ console.error(err); } // catch any mongo error here
finally{ client.close(); } // make sure to close your connection after
}
回答by Sivashanmugam Kannan
This is a General answer for How to use MongoDB with promises in Node.js?
这是如何在 Node.js 中使用带有承诺的 MongoDB的一般答案?
mongodb will return a promise if the callback parameter is omitted
如果省略回调参数,mongodb 将返回一个承诺
Before converting to Promise
在转换为 Promise 之前
var MongoClient = require('mongodb').MongoClient,
dbUrl = 'mongodb://db1.example.net:27017';
MongoClient.connect(dbUrl,function (err, db) {
if (err) throw err
else{
db.collection("users").findOne({},function(err, data) {
console.log(data)
});
}
})
After converting to Promise
转换为 Promise 后
//converted
MongoClient.connect(dbUrl).then(function (db) {
//converted
db.collection("users").findOne({}).then(function(data) {
console.log(data)
}).catch(function (err) {//failure callback
console.log(err)
});
}).catch(function (err) {})
Incase you need to handle multiple request
如果您需要处理多个请求
MongoClient.connect(dbUrl).then(function (db) {
/*---------------------------------------------------------------*/
var allDbRequest = [];
allDbRequest.push(db.collection("users").findOne({}));
allDbRequest.push(db.collection("location").findOne({}));
Promise.all(allDbRequest).then(function (results) {
console.log(results);//result will be array which contains each promise response
}).catch(function (err) {
console.log(err)//failure callback(if any one request got rejected)
});
/*---------------------------------------------------------------*/
}).catch(function (err) {})
回答by Simon Z.
WARNING Edit:
警告编辑:
As John Culviner noted, this answer is deprecated. Use the driver, it comes with promises OOTB.
正如 John Culviner 所指出的,这个答案已被弃用。使用驱动程序,它带有承诺 OOTB。
If you choose to use bluebird as a promise library, you can use bluebirds promisifyAll()
function on MongoClient:
如果您选择使用 bluebird 作为promisifyAll()
Promise库,则可以在 MongoClient 上使用 bluebirds函数:
var Promise = require('bluebird');
var MongoClient = Promise.promisifyAll(require('mongodb').MongoClient);
var url = 'mongodb://localhost:27017/example';
MongoClient.connectAsync(url).then(function (db) {
console.log(db);
}).catch(function(err){
//handle error
console.log(err);
});
回答by Maria Maldini
You need to create a promise that connects to Mongo.
您需要创建一个连接到 Mongo 的承诺。
Then, define your function that uses this promise: myPromise.then(...)
.
然后,定义一个使用这个承诺你的函数:myPromise.then(...)
。
For example:
例如:
function getFromMongo(cb) {
connectingDb.then(function(db) {
db.collection(coll).find().toArray(function (err,result){
cb(result);
});
});
}
here is the full code:
这是完整的代码:
回答by markusthoemmes
You can either use an alternative package, such as mongodb-promise
or promisify the mongodb
package API manually by building your own promises around it or via a promise utility package like bluebird.promisify
您可以使用另一种包装,如mongodb-promise
或promisify的mongodb
通过在周围建造或通过一个承诺工具包就像自己的诺言手动封装APIbluebird.promisify
回答by Dimitar Zafirov
Working solution with MongoDB version > 3.0
MongoDB版本 > 3.0 的工作解决方案
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";
open = (url) => {
return new Promise((resolve,reject) => {
MongoClient.connect(url, (err,client) => { //Use "client" insted of "db" in the new MongoDB version
if (err) {
reject(err)
} else {
resolve({
client
});
};
});
});
};
create = (client) => {
return new Promise((resolve,reject) => {
db = client.db("myFirstCollection"); //Get the "db" variable from "client"
db.collection("myFirstCollection").insertOne({
name: 'firstObjectName',
location: 'London'
}, (err,result)=> {
if(err){reject(err)}
else {
resolve({
id: result.ops[0]._id, //Add more variables if you want
client
});
}
});
});
};
close = (client) => {
return new Promise((resolve,reject) => {
resolve(client.close());
})
};
open(url)
.then((c) => {
clientvar = c.client;
return create(clientvar)
}).then((i) => {
idvar= i.id;
console.log('New Object ID:',idvar) // Print the ID of the newly created object
cvar = i.client
return close(cvar)
}).catch((err) => {
console.log(err)
})
回答by Alex Garcia
I know I am a bit late to the party but I'd like to share an example using ES6
我知道我参加聚会有点晚了,但我想分享一个使用 ES6 的例子
const config = require('config');
const MongoClient = require('mongodb').MongoClient;
var _connection;
var _db;
const closeConnection = () => {
_connection.close();
}
/**
* Connects to mongodb using config/config.js
* @returns Promise<Db> mongo Db instance
*/
const getDbConnection = async () => {
if (_db) {
return _db;
}
console.log('trying to connect');
const mongoClient = new MongoClient(config.mongodb.url, { useNewUrlParser: true });
_connection = await mongoClient.connect();
_db = _connection.db(config.mongodb.databaseName);
return _db;
}
module.exports = { getDbConnection, closeConnection };
I go a bit into more detail here if you want to take a look:
如果你想看一看,我会在这里更详细地介绍一下:
https://medium.com/swlh/how-to-connect-to-mongodb-using-a-promise-on-node-js-59dd6c4d44a7
https://medium.com/swlh/how-to-connect-to-mongodb-using-a-promise-on-node-js-59dd6c4d44a7
回答by mohamed ibrahim
Your approach is almost correct, just a tiny mistake in your argument
你的方法几乎是正确的,只是你的论点中的一个小错误
var MongoClient = require('mongodb').MongoClient var url = 'mongodb://localhost:27017/example' MongoClient.connect(url) .then((db)=> { console.log(db) }) .catch((err)=>console.log(err));