try 使用.findOne方法查找MongoDB条目,但返回以下错误:

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

我觉得这与我的模式文件中的.Models/.Model方法有关,因为我没有收到任何编译信息,即返回undefined类型.我可能做错了什么,所以如果有人帮忙指出,我将不胜感激- 谢谢

文件方案:

const mongoose = require('mongoose')
const Schema = mongoose.Schema

const banSchema = new Schema({
    userId: {
      type: Number,
      required: true
    },
    reason: {
      type: String,
      required: true
    },
    period: {
      type: String,
      required: false,
      default: 'permanent'
    }
})

const name = 'Ban'
//
console.log(typeof(mongoose.models[name] || mongoose.model[name, banSchema])) // Undefined
//
module.exports = mongoose.models[name] || mongoose.model[name, banSchema]

推荐答案

您应该像这样导出您的模型

module.exports = mongoose.model('Ban', banSchema);

你可以阅读更多关于它的here

Node.js相关问答推荐

Mongoose-如何从父文档填充到子文档

使用ReadableStream.管道时NodeJS Crypto Hash不正确

npm错误;无法解析依赖项:npm ERR!对等webpack@;5.x.x;来自@webpack-cli/serve@2.0.5";

通过 Node js 中的 TBA 执行 netsuite REST upsert 操作出现 401 错误

将图像添加到多个产品的条带 checkout 会话中

如何在 require 方法中使用路径与node.js react ?

TypeScript Eslint警告了一个AWS客户端构造函数(dynamodb),但没有警告另一个(s3)

在路由上使用中间件时,Nodejs Express 应用程序失败

如何修改这个flake.nix,这样我就不用每次加载环境都加载nix包了

为什么要加密 CSRF 令牌?

BrowserRouter工作时为什么HashRouter不工作?

为什么我的react 表单不能正常工作?

Mongoose-更新嵌套数组

如何从 github 编译第三方扩展?

Cypress net::ERR_EMPTY_RESPONSE 在真实服务器调用上

eslint - vscode 的可选链接错误

socket.io 发出回调合适吗?

用一级 try ... catch 捕获 JavaScript Promise 中的错误

异步构造函数

Javascript在try块内设置const变量