【发布时间】:2021-08-11 15:29:44
【问题描述】:
我有一个将“userId”订阅到 threadId 的函数,如下所示:
suscribeToThread: async (threadId: IThread["_id"], userId: IUser["_id"]) => {
return await threadModel.updateOne(
{ _id: threadId },
{ $addToSet: { suscribers: userId } }
);
},
我收到以下错误:
Type '{ suscribers: string; }' is not assignable to type '{ readonly [x: string]: any; readonly [x: number]: any; } & NotAcceptedFields<_AllowStringsForIds<LeanDocument<any>>, readonly any[]> & { readonly [key: string]: any; } & { readonly id?: any; ... 4 more ...; readonly replies?: string | AddToSetOperators<...>; } & NotAcceptedFields<...>'.
Type '{ suscribers: string; }' is not assignable to type 'NotAcceptedFields<_AllowStringsForIds<LeanDocument<any>>, readonly any[]>'.
Property 'suscribers' is incompatible with index signature.
Type 'string' is not assignable to type 'never'.ts(2322)
这个错误只发生在 $addToSet、$push 和 $pull 操作符上。
这是线程模型的模型/接口
import mongoose, { Document, Schema } from "mongoose";
import { IComment } from "../comment/commentModel";
import { IUser } from "../user/userModel";
export interface IThread extends Document {
_id: string;
title: string;
timestamp: number;
author: IUser["_id"];
content: string;
locked: boolean;
sticky: boolean;
likedBy: Array<IUser["_id"]>;
dislikedBy: Array<IUser["_id"]>;
viewedBy: Array<IUser["_id"]>;
suscribers: Array<IUser["_id"]>;
replies: Array<IComment["_id"]>;
}
const ThreadSchema = new mongoose.Schema({
title: String,
timestamp: { type: Date, default: Date.now },
author: { type: Schema.Types.ObjectId, ref: "User" },
content: String,
locked: { type: Boolean, default: false },
sticky: { type: Boolean, default: false },
likedBy: [{ type: Schema.Types.ObjectId, ref: "User", default: [] }],
dislikedBy: [{ type: Schema.Types.ObjectId, ref: "User", default: [] }],
viewedBy: [{ type: Schema.Types.ObjectId, ref: "User", default: [] }],
suscribers: [{ type: Schema.Types.ObjectId, ref: "User", default: [] }],
replies: [{ type: Schema.Types.ObjectId, ref: "Comment", default: [] }],
});
export default mongoose.models.Thread ||
mongoose.model<IThread>("Thread", ThreadSchema);
我可以使用 ts-ignore 忽略错误,一切正常,但我认为这不是正确的方法。任何帮助将不胜感激!
【问题讨论】:
-
尝试使用
mongoose.Types.ObjectId而不是Schema.Types.ObjectId例如。suscribers: [{ type: mongoose.Types.ObjectId, ref: "User", default: [] }], -
@TusharGupta-curioustushar 仍然给我同样的错误
-
请提供文档架构
-
@GandalftheWhite 你能详细说明一下吗?
-
Documentexport interface IThread extends Document => Document 的架构。
标签: node.js typescript mongodb mongoose