TypeError: require(...).collection 不是 Object.<anonymous> 的函数

时间:2021-03-08 11:54:13

标签: javascript node.js windows mongodb node-modules

所以我正在尝试使用登录来构建这个应用程序并创建新的帐户功能等。 该应用程序在 localhost:3000 上运行良好,但突然间它停止加载并且我在命令行中出现错误。

下面有错误的文件是 User.js 和 userController.js。 这是 User.js:

const bcrypt = require("bcryptjs")
const usersCollection = require('../db').collection("users")
const validator = require("validator")

let User = function(data){
    this.data = data
    this.errors = []
}

User.prototype.cleanUp = function() {
    if (typeof(this.data.username) != "string") {this.data.username = ""}
    if (typeof(this.data.email) != "string") {this.data.email = ""}
    if (typeof(this.data.password) != "string") {this.data.password = ""}

    //Get rid of any bogus properties
    this.data = {
        username: this.data.username.trim().toLowerCase(),
        email: this.data.email.trim().toLowerCase(),
        password: this.data.password
    }
}

User.prototype.validate = async function(){
    if(this.data.username == ""){this.errors.push("You must provide a username.")}
    if(this.data.username != "" && !validator.isAlphanumeric(this.data.username)) {this.errors.push("Usernames can only include letters and numbers.")}
    if(!validator.isEmail(this.data.email)){this.errors.push("You must provide a valid email address.")}
    if(this.data.password == ""){this.errors.push("You must provide a password.")}
    if(this.data.password.length > 0 && this.data.password.length < 8){this.errors.push("Password must be at least 8 characters.")}
    if(this.data.password.length >50){this.errors.push("Password cannot exceed 50 characters.")}
    if(this.data.username.length > 0 && this.data.username.length < 3){this.errors.push("Username must be at least 3 characters.")}
    if(this.data.username.length >30){this.errors.push("Username cannot exceed 30 characters.")}

    // only if username is valid, then check to see if its already taken
    if (this.data.username.length > 2 && this.data.username.length < 30 && validator.isAlphanumeric(this.data.username)){
        let usernameExists = await usersCollection.findOne({username: this.data.username})
        if (usernameExists) {this.errors.push("That username is already taken.")}
  }

// only if email is valid, then check to see if its already taken
if (validator.isEmail(this.data.email)){
    let emailExists = await usersCollection.findOne({email: this.data.email})
    if(emailExists) {this.errors.push("This email is already registered.")}
  }

}

User.prototype.login = function(){
    return new Promise((resolve, reject) => {
        this.cleanUp()
        usersCollection.findOne({username: this.data.username}).then((attemptedUser) => {
            if (attemptedUser && bcrypt.compareSync(this.data.password, attemptedUser.password)) {
                resolve("congrats")
            } else {
                reject("invalid username / password")
            }
        }).catch(function() {
            reject("Please try again later.")
        })
    })
}

User.prototype.register = function(){
    //Step 1 : validate user data
    this.cleanUp()
    this.validate()
    //Step 2: only if there are no validation errors 
    //then save user data into a database
    if (!this.errors.length){
      //hash user password
      let salt = bcrypt.genSaltSync(10)
      this.data.password = bcrypt.hashSync(this.data.password, salt)  
      usersCollection.insertOne(this.data)
    }
}

module.exports = User

这里是 db.js

const dotenv = require('dotenv')
dotenv.config()
const mongodb = require('mongodb')

mongodb.connect(process.env.CONNECTIONSTRING, {useNewUrlParser: true, useUnifiedTopology: true},function(err, client){
    module.exports = client
    const app = require('./app')
    app.listen(process.env.PORT)
})

这里是 userController.js

const User = require('../models/User')


exports.login = function(req, res){
    let user = new User(req.body)
    user.login().then(function(result){
        req.session.user = {favColor: "gold", username: user.data.username}
        req.session.save(function() {
            res.redirect('/')
        })
    }).catch(function(e){
        req.flash('errors', e)
        req.session.save(function(){
            res.redirect('/')
        })
    })
}

exports.logout = function(req, res){
    req.session.destroy(function() {
        res.redirect('/')
    })
}

exports.register = function(req, res){
    let user = new User(req.body)
    user.register()
    if(user.errors.length){
        user.errors.forEach(function(error) {
            req.flash('regErrors', error)
        })
        req.session.save(function(){
            res.redirect('/')
        })
    } else{
        res.send("There are no errors.")
    }
}

exports.home = function(req, res){
   if (req.session.user) {
    res.render('home-dashboard', {username: req.session.user.username})
   } else{
    res.render('home-guest', {errors: req.flash('errors'), regErrors: req.flash('regErrors')})
   }
}

这里是命令行错误。

TypeError: require(...).collection is not a function
    at Object.<anonymous> (C:\Users\jasmi\OneDrive\Documents\complex-app\models\User.js:2:42)
    at Module._compile (internal/modules/cjs/loader.js:1063:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
    at Module.load (internal/modules/cjs/loader.js:928:32)
    at Function.Module._load (internal/modules/cjs/loader.js:769:14)
    at Module.require (internal/modules/cjs/loader.js:952:19)
    at require (internal/modules/cjs/helpers.js:88:18)
    at Object.<anonymous> (C:\Users\jasmi\OneDrive\Documents\complex-app\controllers\userController.js:1:14)
    at Module._compile (internal/modules/cjs/loader.js:1063:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
[nodemon] app crashed - waiting for file changes before starting...

0 个答案:

没有答案