Reputation: 43
I know there are other questions here asking about the same error, but I couldn't find one specific to my situation.
I try to connect with mongo database:
var dbConn = MongoClient.connect('mongodb://localhost', function (err, client) {
if (err) throw err;
var db = client.db('mytestingdb');
});
and I get an error on this part of the code:
app.post('/thanks', function(req, res) {
if (atendees.checkin === req.body.dbstring) {
dbConn.then(function(db) { //error here
delete req.body._id;
db.collection('feedbacks').insertOne(req.body);
})
res.redirect('/thanks.html')
}
(...)
The idea is to send a form to a database
I tried to follow this tutorial here:
https://programmingmentor.com/post/save-form-nodejs-mongodb/
But the way he tries to connect to the server:
var dbConn = mongodb.MongoClient.connect('mongodb://localhost:27017');
Also gives me an error (db.collection is not a function). From what I've seen here in StackOverflow, that's because of my version of Mongodb. But how can I translate this to the newer version?
Upvotes: 2
Views: 1043
Reputation: 708056
In mongodb 3.0, you can do this:
const MongoClient = require('mongodb').MongoClient;
MongoClient.connect(url).then(client => {
const db = client.db(dbName);
// write code that uses the db here
db.collection(...).insertOne(...).then(...);
}).catch(err => {
// error connecting here
});
This example was taken from the 3.0 doc page here: http://mongodb.github.io/node-mongodb-native/3.0/reference/ecmascriptnext/connecting/
Lots of other ES7 examples here: http://mongodb.github.io/node-mongodb-native/3.0/reference/ecmascriptnext/crud/ which should work in current versions of node.js.
Upvotes: 1