use*_*696 66 javascript mongodb node.js
我一直在尝试发现如何将MongoDB与Node.js一起使用,并且在文档中似乎建议的方法是使用回调.现在,我知道这只是一个偏好问题,但我更喜欢使用承诺.
问题是我没有找到如何在MongoDB中使用它们.的确,我尝试过以下方法:
var MongoClient = require('mongodb').MongoClient;
var url = 'mongodb://localhost:27017/example';
MongoClient.connect(url).then(function (err, db) {
console.log(db);
});
Run Code Online (Sandbox Code Playgroud)
结果是undefined.在这种情况下,似乎这不是这样做的方式.
有没有办法在Node中使用mongo db而不是回调?
Gre*_*een 103
你的方法几乎是正确的,只是你的论证中的一个小错误
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) {})
Run Code Online (Sandbox Code Playgroud)
Pir*_*App 18
由于上面的答案都没有提到如何在没有蓝鸟或q或任何其他花哨的库的情况下这样做,让我加上我的2美分.
以下是使用本机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;
Run Code Online (Sandbox Code Playgroud)
我将open()方法定义为返回promise的方法.要执行插入,下面是我的代码片段
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});
Run Code Online (Sandbox Code Playgroud)
希望有所帮助.如果您有任何建议可以让这更好,请告诉我,因为我愿意提高自己:)
Siv*_*nan 10
这是如何在Node.js中使用MongoDB和promises的一般答案?
如果省略callback参数,mongodb将返回一个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)
});
}
})
Run Code Online (Sandbox Code Playgroud)
转换为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) {})
Run Code Online (Sandbox Code Playgroud)
如果您需要处理多个请求,[需要蓝鸟模块]
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) {})
Run Code Online (Sandbox Code Playgroud)
您还可以进行异步/等待
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
}Run Code Online (Sandbox Code Playgroud)