如何在Node.js中使用带有promise的MongoDB? [英] How to use MongoDB with promises in Node.js?

查看:465
本文介绍了如何在Node.js中使用带有promise的MongoDB?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试发现如何将MongoDB与Node.js一起使用,而在文档中,似乎建议的方法是使用回调。现在,我知道这只是一个偏好问题,但我更喜欢使用promises。

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中使用它们。确实,我尝试过以下方法:

The problem is that I didn't find how to use them with MongoDB. Indeed, I've tried the following:

var MongoClient = require('mongodb').MongoClient;

var url = 'mongodb://localhost:27017/example';

MongoClient.connect(url).then(function (err, db) {
    console.log(db);
});

结果是 undefined 。在这种情况下,这似乎不是这样做的方式。

And the result is undefined. In that case it seems this is not the way to do so.

有没有办法在Node中使用mongo db而不是回调?

Is there any way to use mongo db inside Node with promises instead of callbacks?

推荐答案

你的方法几乎是正确的,只是你论证中的一个小错误

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) {})

这篇关于如何在Node.js中使用带有promise的MongoDB?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆