【发布时间】:2021-11-27 17:12:40
【问题描述】:
我有一个帖子模型:
const PostSchema = new Schema<IPost>(
{
// ...
likes: [{ type: Schema.Types.ObjectId, ref: "User" }],
// ...
}
)
export default model<IPost>("Post", PostSchema)
export interface IPost {
// ...
likes: ObjectId[]
// ...
}
export interface IPostDocument extends Document, IPost {}
我正在尝试切换用户,例如:
export const toggleLike: TController = async (req, res, next) => {
const user = req.user as IUserDocument;
const userId = user._id;
const postId = req.params.postId;
try {
const disliked = await PostModel.findOneAndUpdate(
{ _id: postId, likes: userId },
{ $pull: { likes: userId } }
); // works with no problem
if (disliked)
res.json({ message: `User ${userId} disliked post ${postId}` });
else {
const liked = await PostModel.findOneAndUpdate(
{ _id: postId },
{ $push: { likes: userId } }
); // the $push throws an error "Type instantiation is excessively deep and possibly infinite."
if (liked) res.json({ message: `User ${userId} liked post ${postId}` });
else return next(createError(404, "Post not found"));
}
} catch (error) {
next(createError(500, error as Error));
}
};
mongo $push 运算符抛出错误“类型实例化过深并且可能无限。”
我怀疑它是否有帮助,但错误的描述是:
(属性)喜欢?任意[])[] |任意[])[]|任意[])[]|任意[])[]|任意[])[]|任意[])[]|任意[])[]|任意[])[] |任何[]> | ArrayOperator | 未定义)[]> |未定义
知道发生了什么吗?
【问题讨论】:
-
您介意以有效的 JSON 格式共享示例数据吗?
-
错误提示数据库中的数据不是单级数组,而是数组数组。实际上可能是数组数组数组数组数组数组数组数组数组等等。
-
你能添加你的依赖版本的细节吗?我创建了一个最小的复制here,它适用于
"mongoose": "^6.0.11"、"@types/mongoose": "^5.11.97"和"typescript": "^4.4.4" -
感谢您的 cmets,但问题已解决。在我的界面上,我使用了 ObjectId,但没有从任何地方导入它。一旦我从猫鼬导入它,一切正常。我不知道我使用的另一个 ObjectId 是什么...
标签: typescript mongodb mongoose