“尚未为模型注册架构”仅在填充时出现猫鼬错误

问题描述 投票:0回答:1

我正在使用express和mongoose制作一个项目,我有3个模型(用户、博客、评论)。 除了 populate 之外,所有查询都工作正常, 它给我“模式尚未注册模型”。但是:

  1. 该错误不会发生在所有模型上,它实际上仅适用于用户模型!
  2. 当我尝试将引用作为模型放入模式中时,它本身
    ref: User
    而不是字符串
    ref: "User"
    ,错误消失了!
  3. 我尝试将 ref 小写,但 put 不起作用

我不知道为什么

我想知道是否可以将 ref 作为模型本身
ref: User

这是我的连接


connect = async () => {
  try {
    const conn = await mongoose.connect(DATABASE_URI);
  } catch (error) {
    console.log(error);
  }
};

这是我的用户模式

import mongoose from "mongoose";
import { emailsValidator } from "../utils/emailsValidator";

export const userSchema = new mongoose.Schema(
  {
    username: {
      type: String,
    },
    likes: [
      {
        type: mongoose.Schema.Types.ObjectId,
        ref: "Blog",
      },
    ],
  }
);

export default mongoose.model("User", userSchema);

这是我的博客架构

import mongoose from "mongoose";
import User from "./userModel";
import Comment from "./commentModel";

export const blogSchema = new mongoose.Schema(
  {
    title: {
      type: String,
      unique: true,
    },
    body: {
      type: String,
    },
    comments: [
      {
        type: mongoose.Schema.Types.ObjectId,
        ref: Comment,
      },
    ],
    likedBy: [
      {
        type: mongoose.Schema.Types.ObjectId,
        ref: "User",
      },
    ],

  }
);

export default mongoose.model("Blog", blogSchema);

我也在使用 mongoo atlas 和 nodmon

谢谢

node.js mongodb express mongoose schema
1个回答
0
投票

将 es6 导入更改为 require,解决了!

© www.soinside.com 2019 - 2024. All rights reserved.