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

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

问题描述

我一直在尝试探索如何将 MongoDB 与 Node.js 结合使用,并且在文档中似乎建议的方法是使用回调.现在,我知道这只是一个偏好问题,但我真的更喜欢使用 Promise.

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 和 promise 而不是回调?

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 中使用带有承诺的 MongoDB?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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