最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

nodejs中未处理的承诺拒绝

运维笔记admin9浏览0评论

nodejs中未处理的承诺拒绝

nodejs中未处理的承诺拒绝

mongoDB和NodeJ的新手。我不确定为什么对于以下代码,我会一直无法处理诺言拒绝。

const express = require("express");
const router = express.Router();
const mongoClient = require("mongodb").MongoClient;
const bodyParser = require("body-parser");


router.get("/users",  (req, res) => {

  var MongoClient = require('mongodb').MongoClient;
  var url = "mongodb://localhost:27017/";

  MongoClient.connect(url, function(err, db) {
    if (err) throw err;
    var dbo = db.db("TestDB");
    dbo.collection("users").find({}, function(err, result) {
      if (err) throw err;
      console.log(result.Name);

      res.json(result);    

      db.close();
    });
  });


});


module.exports = router;
回答如下:

看这个例子

const findDocuments = function(db, callback) {
  // Get the documents collection
  const collection = db.collection('documents');
  // Find some documents
  collection.find({}).toArray(function(err, docs) {
    assert.equal(err, null);
    console.log("Found the following records");
    console.log(docs)
    callback(docs);
  });
}

它将帮助您解决问题。

也请查看文档以获取示例:https://mongodb.github.io/node-mongodb-native/3.2/quick-start/quick-start/

我将如何处理您的代码是这样:

MongoClient.connect(url, async (err, db) => {
  if (err) throw err;
  var dbo = db.db("TestDB");
  users = await dbo.collection("users").find({}).toArray()    
  res.json({result:users});    
  db.close();
  });
});

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论