'node js/mongo db: Why trying to add a document to MongoDB keeps trowing me insertOne is not a function?
I'm using Node.js with the MongoDB driver and, when I try to insert an element using the insertOne function it keeps throwing this error:
TypeError: users.insertOne is not a function
at /Users/aleg/sto/servicetools/main.js:64:9
at Layer.handle [as handle_request] (/Users/aleg/sto/servicetools/node_modules/express/lib/router/layer.js:95:5)
at next (/Users/aleg/sto/servicetools/node_modules/express/lib/router/route.js:137:13)
at Route.dispatch (/Users/aleg/sto/servicetools/node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request] (/Users/aleg/sto/servicetools/node_modules/express/lib/router/layer.js:95:5)
at /Users/aleg/sto/servicetools/node_modules/express/lib/router/index.js:281:22
at Function.process_params (/Users/aleg/sto/servicetools/node_modules/express/lib/router/index.js:341:12)
at next (/Users/aleg/sto/servicetools/node_modules/express/lib/router/index.js:275:10)
at /Users/aleg/sto/servicetools/node_modules/body-parser/lib/read.js:130:5
at invokeCallback (/Users/aleg/sto/servicetools/node_modules/raw-body/index.js:224:16)
main.js:
const express = require("express")
const mongo = require("mongodb").MongoClient
const app = express()
const url = "mongodb://localhost:27017"
const port = 5704
const bcrypt = require("bcrypt");
app.use(express.json())
mongo.connect(
url,
{
useNewUrlParser: true,
useUnifiedTopology: true,
},
(err, client) => {
if (err) {
console.error(err)
console.log("! database connection failed.")
process.exit()
return
}
console.log("...loading data from database...")
db = client.db("servicetools")
services = db.collection("services")
settings = db.collection("settings")
users = db.collections("users")
})
}
)
app.post("/STOAdmin/UserAccounts/AddSTOUserAccount", (req, res) => {
users.insertOne(
{
username: req.body.username,
password: req.body.password,
admin: req.body.admin,
enabled: req.body.enabled
},
(err, result) => {
if (err) {
console.error(err)
res.status(500).json({ err: err })
return
}
res.status(200).json({ ok: true })
}
)
})
app.listen(port, () => console.log("backend ready for requests"))
The code uses Express for the API Requests and it can't insert the elements from them throwing the error.
Solution 1:[1]
I resolved the problem, I did a typo in the users declaration.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Giovanni Patruno |
