You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决TypeScript中"Object literal may only specify known properties"错误?

解决Next.js + Mongoose中的FilterQuery类型错误

问题分析

你遇到的两个TypeScript错误,本质是FilterQuery的类型参数使用错误:

  • 错误1:'title' does not exist in type 'FilterQuery<Model<any, {}, {}, {}, any, any>>'
  • 错误2:'answers' does not exist on type 'FilterQuery<Model<any, {}, {}, {}, any, any>>'

原因是定义query时,你用了FilterQuery<typeof Question>,但typeof Question是Mongoose的Model类型,不是自定义的IQuestion文档接口。FilterQuery需要基于文档的类型(即IQuestion),才能识别文档中的title、answers等属性。

解决方案

将FilterQuery的类型参数从typeof Question改为IQuestion,同时确保已导入IQuestion接口:

修改后的核心代码片段:

// 确保导入IQuestion接口
import Question, { IQuestion } from "@/models/Question";
import { FilterQuery } from "mongoose";

export async function getQuestions(params: GetQuestionsParams) {
  try {
    connectToDatabase();

    const { searchQuery, filter, page = 1, pageSize = 10 } = params;
    const skipAmount = (page - 1) * pageSize;

    // 关键修改:将typeof Question改为IQuestion
    const query: FilterQuery<IQuestion> = {};

    if (searchQuery) {
      const escapedSearchQuery = searchQuery.replace(
        /[.*+?^${}()|[\]\\]/g,
        "\\$&"
      );
      query.$or = [
        { title: { $regex: new RegExp(escapedSearchQuery, "i") } },
        { content: { $regex: new RegExp(escapedSearchQuery, "i") } },
      ];
    }

    let sortOptions = {};

    switch (filter) {
      case "newest":
        sortOptions = { createdAt: -1 };
        break;
      case "frequent":
        sortOptions = { views: -1 };
        break;
      case "unanswered":
        // 现在TypeScript会识别answers属性
        query.answers = { $size: 0 };
        break;
      default:
        break;
    }

    // 后续代码保持不变
    const questions = await Question.find(query)
      .populate({ path: "tags", model: Tag })
      .populate({ path: "author", model: User })
      .skip(skipAmount)
      .limit(pageSize)
      .sort(sortOptions);

    const totalQuestions = await Question.countDocuments(query);
    const isNext = totalQuestions > skipAmount + questions.length;

    return { questions, isNext };
  } catch (error) {
    console.log(error);
    throw error;
  }
}

额外说明

  • Mongoose的FilterQuery<T>泛型要求T是文档接口类型(比如你定义的IQuestion),而不是Model类型。Model类型是用于操作数据库的类,不包含文档的具体属性定义。
  • 确保IQuestion接口正确继承了Mongoose的Document,且所有属性和Schema定义一致,这样TypeScript才能正确推断查询对象的类型。

内容的提问来源于stack exchange,提问作者Muhammadali

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 23:45:14