Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js MongoDb节点js.then.fail_Node.js_Mongodb_Promise - Fatal编程技术网

Node.js MongoDb节点js.then.fail

Node.js MongoDb节点js.then.fail,node.js,mongodb,promise,Node.js,Mongodb,Promise,我如何编写代码,但使用.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){

我如何编写代码,但使用.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); 
        }
    });
});

请尝试以下代码段:

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

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

/config/mongodb.js

//app.js


基本上,如果你有
.findOne({stuff},function(){…})
,去掉第一个逗号后的所有东西,用
替换,然后开始链接
。然后(function(){…})
到它上面。另外,为了澄清一下,你可以用
函数(某物)替换我所有的
(某物)=>{/code>{
。检查fat arrow函数。我尝试过这样做,但在说db.get().collection(“type”).findOne()不是一个函数时出错。这是因为您如何实例化
db
。它需要是一个解决承诺,以将其链接起来。
 // 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);
     });
 });
 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}`);
   });