You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 specific users collection object that has methods like insertOne.

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

  1. Password Hashing: I added bcrypt.hash to your code because storing plain-text passwords is a huge security risk. Always hash user passwords before saving them to the database.
  2. Scope & Initialization: Moving your route definitions and app.listen inside the mongo.connect callback 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.
  3. Use let/const: Declare your database/collection variables with let (since they're reassigned) to avoid polluting the global scope.

内容的提问来源于stack exchange,提问作者AleG

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 15:14:06