猫鼬在 NextJS 中缓存的 dbConnect 显示问题

分享于2022年07月17日 mongodb mongoose mongoose-schema next.js node.js 问答
【问题标题】:猫鼬在 NextJS 中缓存的 dbConnect 显示问题(Mongoose cached dbConnect in NextJS showing issue)
【发布时间】:2022-06-30 11:43:13
【问题描述】:

我在 NextJS 应用程序中使用 Mongoose 连接到我在 MongoDB Atlas 中的数据库。

以下是精简后的相关代码:

dbConnect.js

/**
 *      MongoDB Connection
 * 
 *  */
import mongoose from 'mongoose'

if (! process.env.MONGODB_URL) {
  throw new Error(
    'Please define the MONGODB_URL environment variable inside .env.local'
  )
}

/**
 * Global is used here to maintain a cached connection across hot reloads
 * in development. This prevents connections growing exponentially
 * during API Route usage.
 */
let cached = global.mongoose

if (!cached) {
  cached = global.mongoose = { conn: null, promise: null }
}

async function dbConnect() {
  if (cached.conn) {
    return cached.conn
  }

  if (!cached.promise) {
    const opts = {
      useNewUrlParser: true,
      useUnifiedTopology: true,
      bufferCommands: false,
    //   bufferMaxEntries: 0,
    //   useFindAndModify: false,
    //   useCreateIndex: true,
    }

    cached.promise = mongoose.connect(process.env.MONGODB_URL, opts).then((mongoose) => {
      return mongoose
    })
  }
  cached.conn = await cached.promise
  return cached.conn
}

export default dbConnect

这就是我定义用户模型的方式:

/models/User.js

import mongoose from 'mongoose';
var Schema = mongoose.Schema;

var UserSchema = new Schema({

    name: {
        type: String,
        // required: [true, "Name is mandatory"]
    },      

    email: {
        type: String,
    },    

});

// mongoose.models = {}; 

var User = mongoose.models.User || mongoose.model('User', UserSchema);  

export default User;     

我已经定义了自定义辅助函数以使其更容易。所以基本上这些函数都会从数据库中返回结果。

/functions/user_funcs.js

import User from '../models/User'
import Book from '../models/Book'

//-- get all Users
const getAllUsers = async () => {
    try{
        //-- get the details
        let users = await User.find({})
            .collation({locale: "en" })     //-- for case insensitive sorting
            .select('name email')           
            .sort('name')
            .exec()

        if( users.length > 0 ){
            //-- format the data
            let users_formatted = users.map( p => {
                p = p.toObject()
            
                //-- convert to strings    
                p._id = p._id.toString()               
        
                return p
            } )

            return users_formatted
        }
                         
    }
    catch(e){
        console.log( e )        
    }

    return []   
}


//-- get Books of User
const getBooksOfUser = async (user_id) => {
    try{
        //-- get the details
        let books = await Book.find({})            
            .select('name')
            .where( 'author' ).equals( user_id )
            .sort('name')
            .exec()

        if( books.length > 0 ){
            //-- format the data
            let books_formatted = books.map( p => {
                p = p.toObject()
            
                //-- convert to strings    
                p._id = p._id.toString()               
        
                return p
            } )

            return books_formatted
        }
                         
    }
    catch(e){
        console.log( e )        
    }

    return []   
}

export {
    getBooksOfUser,
    getAllUsers
}

/pages/users.js

import Link from 'next/link'
import Image from 'next/image'    

import Footer from "../components/common/Footer";
import Header from "../components/common/Header";

import styles from '../styles/Users.module.css'

import dbConnect from '../lib/dbConnect';

import { getAllUsers } from '../functions/user_funcs';


export default function Users({ users_data }){


    return (
        <>
            
{ users_data.map( (item, i) => (
{ item.name }
) ) }
) } export async function getStaticProps(context) { //-- db connection await dbConnect() //-- get all users const users_data = await getAllUsers() return { props: { users_data , }, revalidate: 100 } }

问题是,当我访问 http://localhost:3000/users 页面时,它会抛出以下错误:

TypeError: Cannot read properties of undefined (reading 'User')

错误突出显示 /models/User.js 中的以下行:

var User = mongoose.models.User || mongoose.model('User', UserSchema);

有什么想法吗?


【解决方案1】:

你最后解决了吗?所以不会让我评论,但我建议改变 var User = mongoose.models.User || mongoose.model('User', UserSchema);

module.exports = mongoose.model("User", User)