【问题标题】:MongoDb Node js .then .failMongoDb 节点 js .then .fail
【发布时间】:2017-12-03 20:29:45
【问题描述】:

我如何编写代码来做同样的事情,但使用 .then 和 .fail

在下面的代码中,第 1 行的 db.get() 将连接返回为 db.collection('......).find({}) 中的“db”。换句话说 db.get() 与 db 是一样的;我在一个单独的模块中连接到 mongodb。

db.get().collection('type').findOne({"_id":objId}, function(err, typeInfoResult){
    try{
        if(err){
            res.send(errMsg);
        } 
        else{
            var business_id = typeInfoResult.business_id;
            db.get().collection('business_info').findOne({"_id":ObjectID(business_id)}, function(err, businessInfoQuery){
                if(err){
                    res.send(errMsg);
                }
                else{
                    var completetypeDetail = {typeDetails:typeInfoResult, BusinessDetails:businessInfoQuery};
                    res.send(completetypeDetail);
                }
            })
        }
    }catch(err){
        res.send(errMsg); 
        }
    });
});

【问题讨论】:

    标签: node.js mongodb promise


    【解决方案1】:

    在下面试试这个:

    db.collection('type').find({"_id":objId}).toArray(function(err, typeInfoResult){
    try{
        if(err){
            res.send(errMsg);
        } 
        else{
            var business_id = typeInfoResult.business_id;
            db.get().collection('business_info').findOne({"_id":ObjectID(business_id)}, function(err, businessInfoQuery){
                if(err){
                    res.send(errMsg);
                }
                else{
                    var completetypeDetail = {typeDetails:typeInfoResult, BusinessDetails:businessInfoQuery};
                    res.send(completetypeDetail);
                }
            })
        }
    }catch(err){
        res.send(errMsg); 
        }
    });
    

    【讨论】:

      【解决方案2】:

      这是一个例子,因为我前几天刚刚连接了 MongoDB:

      ./config/mongodb.js

       // Load MongoDB Driver
       const MongoClient = require('mongodb').MongoClient;
      
       /**
        *
        * Instantiate MongoDB Connection
        *
        * Additional options:
        * https://docs.mongodb.com/manual/reference/connection-string/#connection-string-options
        */
      
       // Connect database
       export const MongoDB = new Promise((resolve, reject) => {
         // MongoDB Connection Info
         let url = `mongodb://${Singleton.currentConfig.databases.mongodb.user}:`;
         url += `${Singleton.currentConfig.databases.mongodb.password}@`;
         url += `${Singleton.currentConfig.databases.mongodb.host}:`;
         url += `${Singleton.currentConfig.databases.mongodb.port}/?authMechanism=DEFAULT&`;
         url += `authSource=${Singleton.currentConfig.databases.mongodb.db}`;
      
         // Use Connect Method to connect to the Server
         MongoClient.connect(url)
      
           .then((db) => {
             console.log('Casually connected correctly to server.');
             resolve(db);
           })
      
           .catch((error) => {
             console.log(`MongoDB Connection Error: ${error}`);
             reject(error);
             process.exit(0);
           });
       });
      

      ./app.js

       const MongoDB = require('./config/mongodb');
       // or
       // import MongoDB from './config/mongodb';
      
       // Acquire an object
       userDetails = { email: 'async@await.com', firstName: 'Uwot', lastName: 'Mate' };
      
       // Create a user
       MongoDB.collection('users').insertOne(userDetails)
      
         .then((done) => {
           console.log(`Added: ${done}`);
         })
      
         .catch((error) => {
           throw new Error(`Fecal's on fire, yo: ${error}`);
         });
      

      【讨论】:

      • 基本上,在你有.findOne({stuff}, function() { ... }) 的地方,去掉第一个逗号之后的所有内容并用) 替换它,然后开始将.then(function() { ... }) 链接到它上面。
      • 另外,为了澄清,您可以将我所有的(something) => { 替换为function(something) {。查看粗箭头函数。
      • 我尝试这样做,但我收到错误消息说 db.get().collection("type").findOne() 不是函数。
      • 这是因为您如何实例化db。它需要是一个已解决的承诺才能将其链接起来。
      猜你喜欢
      • 2014-08-30
      • 2018-06-15
      • 2016-02-13
      • 1970-01-01
      • 2018-03-28
      • 2017-07-23
      • 2019-01-09
      • 2018-07-04
      • 2021-11-18
      相关资源
      最近更新 更多