Node.js结合MongoDB驱动调用insertOne时出现TypeError: users.insertOne is not a function错误的排查与解决
Fix: TypeError: users.insertOne is not a function in Node.js + MongoDB Driver
Great catch on the root cause of your error! Let's break this down and get your code working properly.
Why This Error Happens
You're using db.collections("users") (plural) to try and get your users collection, but that's not the right method:
db.collections()(without parameters) returns a list of all collections in your database, not a single collection instance.- What you need is
db.collection("users")(singular), which returns the specificuserscollection object that has methods likeinsertOne.
Corrected Code
Here's your fixed main.js with the key correction and a small syntax fix (you had an extra closing bracket in the mongo.connect callback):
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()) // Declare these variables at the top to avoid scope issues let db, services, settings, users; 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.collection("users") // Fixed: singular collection() instead of collections() // Optional: Move route definitions inside the connect callback to ensure collections are initialized app.post("/STOAdmin/UserAccounts/AddSTOUserAccount", (req, res) => { // Also, consider hashing passwords before storing! bcrypt.hash(req.body.password, 10, (hashErr, hashedPassword) => { if (hashErr) { console.error(hashErr) return res.status(500).json({ err: hashErr }) } users.insertOne( { username: req.body.username, password: hashedPassword, // Store hashed password instead of plain text 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 }) } ) }) }) // Start server only after database connection is successful app.listen(port, () => console.log("backend ready for requests")) } )
Extra Recommendations
- Password Hashing: I added
bcrypt.hashto your code because storing plain-text passwords is a huge security risk. Always hash user passwords before saving them to the database. - Scope & Initialization: Moving your route definitions and
app.listeninside themongo.connectcallback ensures that your collections are fully initialized before handling requests. This prevents potential "users is undefined" errors if the server starts before the database connection is complete. - Use
let/const: Declare your database/collection variables withlet(since they're reassigned) to avoid polluting the global scope.
内容的提问来源于stack exchange,提问作者AleG
相关产品推荐
相关产品推荐

