Good afternoon, I just started learning Node.JS, so don’t be strict) I’m trying to create an application with data exchange with the MongoDB database, but I can’t execute a POST request to the database.

An error occurs

TypeError: db.collection is not a function

And for some reason in the console writes

connection accepted from 127.0.0.1 Oc1061 # 4 (1 connection now open)

That is the wrong port.

var express = require('express'); var app = express(); var bodyParser = require('body-parser'); var MongoClient = require('mongodb').MongoClient; var db = null; app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); app.get('/user',function(req, res){ res.send(users); }) app.post('/user',function(req, res){ var user = { login: req.body.login }; db.collection('users').insert(user, function(err, result){ if(err){ console.log(err); return res.sendStatus(500); }; res.send(user); db.close(); }) res.send(user); }) MongoClient.connect('mongodb://localhost:27017/chat_bd', function(err, database){ if(err){return console.log(err)} db = database; app.listen(4040, function(){ //in 4040 port(http://localhost:4040/) console.log('All Is OK') }); }) 

The latest version of MongoDB, driver version 3.0.3

    1 answer 1

    You have in the code porridge. The first is that it is necessary to read. The second is something like that (I have nowhere to check, but in theory it should work):

      var express = require('express'); var app = express(); var bodyParser = require('body-parser'); var MongoClient = require('mongodb').MongoClient; app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); app.get('/user',function(req, res){ res.send(users); }) //POST http://localhost:4040/user app.post('/user',function(req, res){ let user = { login: req.body.login }; my_connect.db.collection('users').insert(user, function(err, result){ if(err){ console.log(err); return res.sendStatus(500); }; res.send(user); db.close(); }) my_connect.res.send(user); }) const my_connect = MongoClient.connect('mongodb://localhost:27017/chat_bd', function(err, database){ if(err){return console.log(err)} }) //chat_bd єто и есть наша БД поєтому не нужно создавать отдельную переменную БД app.listen(4040, function(){ //in 4040 port(http://localhost:4040/) console.log('All Is OK') }); 

    In general, try using Mongoose to work with a Mongo database on a node.