Home > Software engineering >  TypeError: db.collection(...).save is not a function
TypeError: db.collection(...).save is not a function

Time:04-14

I am trying to submit data with an html form and send the data to my mongodb database using nodejs/expres crud operations, but I am receiving the error:

TypeError: db.collection(...).save is not a function

I have two files, server.js and index.html.

index.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <form action="/quotes" method="POST"> 
         <input type="text" placeholder="name" name="name">  
         <input type="text" placeholder="quote" name="quote">  
         <button type="submit">Submit</button>
    </form>
</body>
</html>

My mongodb db is "notesDB" and collection is "quotes" server.js:

const express = require('express');
const app = express();
const bodyParser = require('body-parser')
const MongoClient = require('mongodb').MongoClient

var db

MongoClient.connect('mongodb srv://username:[email protected]/notesDB', (err, database) => {
  if (err) return console.log(err)
  db = database.db('notesDB')
  app.listen(3000, () => {
    console.log('listening on 3000')
  })


})

app.use(bodyParser.urlencoded({extended: true}))


app.get('/', (req, res) => {
    res.sendFile(__dirname   '/index.html')
})

app.post('/quotes', (req, res) => {
    db.collection('quotes').save(req.body, (err, result) => {
      if (err) return console.log(err)
      console.log('saved to database')
      res.redirect('/')
    })
  })

The error in the title has many other solutions on stack overflow, the most popular being

It's mongodb version error which you have installed in your project. You should run npm install [email protected] --save in your project

When I tried this I had 4 critical vulnerabilities in my code and multiple other errors to which I realized I should just use the most up to date version, so I do not like that solution.

The second solution that I tried was moving the crud opperations, namely the get and post under the mongodb connection, I tried this due to the other posts about this error being structured this way, which did not change anything:

MongoClient.connect('mongodb srv://username:[email protected]/notesDB', (err, database) => {
  if (err) return console.log(err)
  db = database.db('notesDB')
  app.listen(3000, () => {
    console.log('listening on 3000')
  })
  
    app.use(bodyParser.urlencoded({extended: true}))


    app.get('/', (req, res) => {
        res.sendFile(__dirname   '/index.html')
    })

    app.post('/quotes', (req, res) => {
        db.collection('quotes').save(req.body, (err, result) => {
        if (err) return console.log(err)
        console.log('saved to database')
        res.redirect('/')
        })
    })

})

I read some more about using client instead of database thus I replaced the database with client and tried that way, which resulted in the same error. Since I got this code from a tutorial I went a head and downloaded the final version of the code from his github and booted up the project and it worked, thus I am looking extra hard for why this is not working since it definitely should be, the code is here if that helps at all since the code is so similar but actually works.

Edit: I am getting the listening on 3000, its submission of the form that I am getting the error, just for clarification.

CodePudding user response:

.save() has been deprecated instead of that .save() you can use .insertOne() or .insertMany() or.updateOne({upsert:true})

You can write your code like below by replacing .save() with .insertOne()

app.post('/quotes', (req, res) => {
    db.collection('quotes').insertOne(req.body, (err, result) => {
      if (err) return console.log(err)
      console.log('saved to database')
      res.redirect('/')
    })
  })

For further CRUD operation you can follow below docs

https://www.mongodb.com/developer/quickstart/node-crud-tutorial/?_ga=2.210725788.862450187.1649763419-1339553468.1649528473&_gac=1.209527078.1649528473.EAIaIQobChMIt8KGr8yH9wIVg3ZgCh3-2gcdEAAYASABEgJH8vD_BwE

  • Related