MongoDb节点js .then .fail

时间:2017-06-30 00:39:43

标签: node.js mongodb promise

如何使用.then和.fail

编写执行相同操作的代码

在下面的代码中,第1行中的db.get()将连接返回为" db"在db.collection中(' ......)。find({})。换句话说,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); 
        }
    });
});

2 个答案:

答案 0 :(得分:0)

请尝试以下代码段:

## dummy data. expand.grid gives all combinations of its arguments
## I chose 50 values of vis to generate a nice smooth curve
## better to calculate means on the fly than hard-code them
##    to avoid bugs
pred_dat = expand.grid(
    age = mean(sampleData$age),
    vis = seq(from = min(sampleData$vis), to = max(sampleData$vis), length.out = 50),
    caf = factor(0:1)
)

## create a model matrix and multiply by the fixed coefs to generate predictions
pred_dat$pred = as.vector(model.matrix(~ age + vis + caf, data = pred_dat) %*% fixCoef)

答案 1 :(得分:0)

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

  

./配置/ 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}`);
   });