返回

node.js-Mongoose在NextJS中缓存的dbConnect显示问题

发布时间:2022-07-08 15:31:04 253

我使用Mongoose在我的NextJS应用程序中连接到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:无法读取未定义的属性(读取“User”)

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

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

有什么想法吗?

特别声明:以上内容(图片及文字)均为互联网收集或者用户上传发布,本站仅提供信息存储服务!如有侵权或有涉及法律问题请联系我们。
举报
评论区(1)
按点赞数排序
用户头像