Node.js TypeError:无法读取属性';然后';未定义节点js的定义

Node.js TypeError:无法读取属性';然后';未定义节点js的定义,node.js,express,routes,Node.js,Express,Routes,TypeError:无法读取未定义的属性“then” 你能帮我修一下吗?多谢各位 var express = require('express'); var path = require('path'); var bodyParser = require('body-parser'); var mongodb = require('mongodb'); var dbConn = mongodb.MongoClient.connect('mongodb://localhost:27017',

TypeError:无法读取未定义的属性“then” 你能帮我修一下吗?多谢各位

var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var mongodb = require('mongodb'); 

var dbConn = mongodb.MongoClient.connect('mongodb://localhost:27017', 
function(err, db) {
    if(err){
        throw err;
    }else{
        console.log("connected");
    }
})

var app = express();

app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.resolve(__dirname, './')));

app.post('/post-feedback', function (req, res) {
    dbConn.then(function(db) {
        delete req.body._id; // for safety reasons
        db.collection('feedbacks').insertOne(req.body);
    });    
        res.send('Data received:\n' + JSON.stringify(req.body));
    });

app.get('/view-feedbacks',  function(req, res) {
        dbConn.then(function(db) {
        db.collection('feedbacks').find({}).toArray().then(function(feedbacks) {
            res.status(200).json(feedbacks);
        });
    });
});

app.listen(process.env.PORT || 3000, process.env.IP || '0.0.0.0' );
TypeError:无法读取未定义的属性“then”
你能帮我修一下吗?谢谢。

试试这个,dbConn不是承诺

var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var mongodb = require('mongodb'); 

var dbConn = mongodb.MongoClient.connect('mongodb://localhost:27017', 
function(err, db) {
    if(err){
        throw err;
    }else{
        console.log("connected");
    }
})

var app = express();

app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.resolve(__dirname, './')));

app.post('/post-feedback', function (req, res) {
    dbConn.then(function(db) {
        delete req.body._id; // for safety reasons
        db.collection('feedbacks').insertOne(req.body);
    });    
        res.send('Data received:\n' + JSON.stringify(req.body));
    });

app.get('/view-feedbacks',  function(req, res) {
        dbConn.then(function(db) {
        db.collection('feedbacks').find({}).toArray().then(function(feedbacks) {
            res.status(200).json(feedbacks);
        });
    });
});

app.listen(process.env.PORT || 3000, process.env.IP || '0.0.0.0' );
app.post('/post-feedback', function (req, res) {
    mongoose.connection.db.collection('feedbacks', function (err, collection) {
        collection.insertOne(req.body);
        res.send('Data received:\n' + JSON.stringify(req.body));
    });

    // OR

    const Model = mongoose.model('feedbacks');
    let model = new Model();
    model = Object.assign(model, req.body);
    model.save().then((result) => {
        res.send('Data received:\n' + JSON.stringify(req.body));
    });
});

试试这个,dbConn不是承诺

app.post('/post-feedback', function (req, res) {
    mongoose.connection.db.collection('feedbacks', function (err, collection) {
        collection.insertOne(req.body);
        res.send('Data received:\n' + JSON.stringify(req.body));
    });

    // OR

    const Model = mongoose.model('feedbacks');
    let model = new Model();
    model = Object.assign(model, req.body);
    model.save().then((result) => {
        res.send('Data received:\n' + JSON.stringify(req.body));
    });
});

以下方法应该让您开始,但不应将其用于生产
(参考:)。通读另一个生产初学者

var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var mongodb = require('mongodb'); 

var dbConn = function() {
    return new Promise((resolve, reject) => {
        mongodb.MongoClient.connect('mongodb://localhost:27017', 
            function(err, db) {
                if(err){
                    return reject(err);
                }else{
                    return resolve(db);
                } 
        });
    });
}

var app = express();

app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.resolve(__dirname, './')));

app.post('/post-feedback', function (req, res) {
    dbConn()
    .then(function(db) {
        delete req.body._id; // for safety reasons
        db.collection('feedbacks').insertOne(req.body);
        res.send('Data received:\n' + JSON.stringify(req.body));
    })
    .catch(err => {
        console.log(err)
        res.send('Error');
    })
});

app.get('/view-feedbacks',  function(req, res) {
        dbConn()
        .then(function(db) {
            db.collection('feedbacks').find({}).toArray().then(function(feedbacks) {
                res.status(200).json(feedbacks);
            });
        })
        .catch(err => {
            console.log(err);
            res.status(500).json({});
        });
});

app.listen(process.env.PORT || 3000, process.env.IP || '0.0.0.0' );

生产启动程序: 理想情况下,在文件
db.js

let mongoClient = require('mongodb').MongoClient,
   logger = require('winston');

function DATABASE() {
   this.dbObj = null;
   this.myCollection = null; // You will need to add more collections here
}

DATABASE.prototype.init = function (config, options) {
   let self = this;
   self.config = config; //can pass a config for different things like port, ip etc.
   self.logger = logger;

   return new Promise(function (resolve, reject) {
      if (self.initialized) {
         return resolve(self);
      }
      let connectionUri = "mongodb://localhost:27017";     //self.config.mongo.connectionUri;
      mongoClient.connect(connectionUri, {native_parser: true}, function     (err, db) {
         if (err) {
            reject(err);
         }
         else {
            self.dbObj = db;
            self.myCollection = db.collection('myCollection');
            self.initialized = true;
            self.logger.info("db init success");
            return resolve(self);
         }
      });
   });
};

var dbObj = null;

var getdbObj = function () {
   if (!dbObj) {
      dbObj = new DATABASE();
   }
   return dbObj;
}();

module.exports = getdbObj;

在主应用程序启动文件中,您将有以下内容:

let dbObj = require('./db.js');
dbObj.init()
.then(db => {
     console.log('db initialized successfully');
     //db.dbObj.collection('myCollection').find()
     //or
     //db.myCollection.find() because this has been already initialized in db.js
     var app = express();
     app.use(bodyParser.urlencoded({ extended: false }));
     app.use(express.static(path.resolve(__dirname, './')));

     app.post('/post-feedback', function (req, res) {
         delete req.body._id; // for safety reasons
         db.dbObj.collection('feedbacks').insertOne(req.body);
         res.send('Data received:\n' + JSON.stringify(req.body));
     });

     app.get('/view-feedbacks',  function(req, res) { 
         //db.collection('feedbacks')
     });

     app.listen(process.env.PORT || 3000, process.env.IP || '0.0.0.0' )
})
.catch(err => console.log(err));

以下方法应该让您开始,但不应将其用于生产
(参考:)。通读另一个生产初学者

var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var mongodb = require('mongodb'); 

var dbConn = function() {
    return new Promise((resolve, reject) => {
        mongodb.MongoClient.connect('mongodb://localhost:27017', 
            function(err, db) {
                if(err){
                    return reject(err);
                }else{
                    return resolve(db);
                } 
        });
    });
}

var app = express();

app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.resolve(__dirname, './')));

app.post('/post-feedback', function (req, res) {
    dbConn()
    .then(function(db) {
        delete req.body._id; // for safety reasons
        db.collection('feedbacks').insertOne(req.body);
        res.send('Data received:\n' + JSON.stringify(req.body));
    })
    .catch(err => {
        console.log(err)
        res.send('Error');
    })
});

app.get('/view-feedbacks',  function(req, res) {
        dbConn()
        .then(function(db) {
            db.collection('feedbacks').find({}).toArray().then(function(feedbacks) {
                res.status(200).json(feedbacks);
            });
        })
        .catch(err => {
            console.log(err);
            res.status(500).json({});
        });
});

app.listen(process.env.PORT || 3000, process.env.IP || '0.0.0.0' );

生产启动程序: 理想情况下,在文件
db.js

let mongoClient = require('mongodb').MongoClient,
   logger = require('winston');

function DATABASE() {
   this.dbObj = null;
   this.myCollection = null; // You will need to add more collections here
}

DATABASE.prototype.init = function (config, options) {
   let self = this;
   self.config = config; //can pass a config for different things like port, ip etc.
   self.logger = logger;

   return new Promise(function (resolve, reject) {
      if (self.initialized) {
         return resolve(self);
      }
      let connectionUri = "mongodb://localhost:27017";     //self.config.mongo.connectionUri;
      mongoClient.connect(connectionUri, {native_parser: true}, function     (err, db) {
         if (err) {
            reject(err);
         }
         else {
            self.dbObj = db;
            self.myCollection = db.collection('myCollection');
            self.initialized = true;
            self.logger.info("db init success");
            return resolve(self);
         }
      });
   });
};

var dbObj = null;

var getdbObj = function () {
   if (!dbObj) {
      dbObj = new DATABASE();
   }
   return dbObj;
}();

module.exports = getdbObj;

在主应用程序启动文件中,您将有以下内容:

let dbObj = require('./db.js');
dbObj.init()
.then(db => {
     console.log('db initialized successfully');
     //db.dbObj.collection('myCollection').find()
     //or
     //db.myCollection.find() because this has been already initialized in db.js
     var app = express();
     app.use(bodyParser.urlencoded({ extended: false }));
     app.use(express.static(path.resolve(__dirname, './')));

     app.post('/post-feedback', function (req, res) {
         delete req.body._id; // for safety reasons
         db.dbObj.collection('feedbacks').insertOne(req.body);
         res.send('Data received:\n' + JSON.stringify(req.body));
     });

     app.get('/view-feedbacks',  function(req, res) { 
         //db.collection('feedbacks')
     });

     app.listen(process.env.PORT || 3000, process.env.IP || '0.0.0.0' )
})
.catch(err => console.log(err));
工作正常。
如果您从mongodb获得任何类型错误(未处理的PromisejectionWarning:TypeError:db.collection不是函数)。只需将mongodb的版本更改为-

“mongodb”:“^2.2.33”

工作正常。
如果您从mongodb获得任何类型错误(未处理的PromisejectionWarning:TypeError:db.collection不是函数)。只需将mongodb的版本更改为-

“mongodb”:“^2.2.33”


dbConn不是承诺。你可以在这里得到一些指示。参考:dbConn不是承诺。你可以在这里得到一些指示。参考: