所以,我必须更新主界面中的一些数据,问题是,当我尝试这样做时,它会抱怨,因为 .save()
未定义
所以我创建了另一个接口来访问该数据,以便 extends Document
这样我就可以访问 .save()
但是,这是新的错误....
const theComment: IComment
Type 'Comment' is missing the following properties from type 'IComment': $getAllSubdocs, $ignore, $isDefault, $isDeleted, and 47 more.
这是我的代码
我想更新什么(问题是评论)
export const editComment = async (req: Request, res: Response) => {
const {publicationId} = req.params;
const { identifier, body, commentId } = req.body;
// Check id's
if (!mongoose.Types.ObjectId.isValid(identifier!))
return res.status(400).json({ Message: "identifier not valid" });
if (!mongoose.Types.ObjectId.isValid(publicationId!))
return res.status(400).json({ Message: "identifier not valid" });
if (!mongoose.Types.ObjectId.isValid(commentId!))
return res.status(400).json({ Message: "identifier not valid" });
// Find pub
const thePub: Ipub = await Publication.findById(publicationId);
// Find user
const theUser: Iauth = await User.findById(identifier);
// Find comment, make sure that comment is from that user
const theComment: IComment = thePub.comments!.find((f) => f.id === commentId && f.identifier === theUser.id)!;
if(!theComment) return res
.status(405)
.json({ Message: "You are not the owner of the comment || Comment doesn't exist" })
// Make sure body is not empty
if(!body) return res.status(404).json({Message: 'No data provided'})
try {
// Update comment and perfil if it has changed
theComment.body = body;
theComment.perfil = theUser.perfil;
await theComment.save()
return res.json(theComment)
} catch (err) {
console.log(err);
return res.status(500).json({ Error: "the API failed" });
}
};
主界面
export interface Ipub extends Document {
id?: string;
body: string;
photo: string;
creator: {
name: string;
perfil?: string;
identifier: string;
};
likes?: Likes[];
comments?: Comment[];
createdAt: string;
}
我想在主界面内更新的数据界面
export interface IComment extends Document {
id?: string;
body: string;
name: string;
perfil?: string;
identifier: string;
createdAt: string;
likesComments?: Likes[];
}
我能做什么?我该如何解决?
感谢您的时间社区!
答案 0 :(得分:1)
TS 编译器说 Comment
接口描述的对象没有 .save()
方法。我认为它不应该有,因为它不是 MongoDB 文档。
当你从 Document
接口继承所有 props 时,编译器抛出错误,说类型 Comment
& IComment
不兼容,因为第二个有 Document
props,第一个没有。要修复它,您应该像这样直接转换类型:
const theComment = thePub.comments!.find((f) => f.id === commentId && f.identifier === theUser.id)! as IComment;
但为了更新评论,您必须更新“整个”Publication
文档(例如,通过使用 aggregate):
Publication.update(
{
"id": publicationId,
"comments.id": commentId,
"comments.identifier": theUser.id,
},
{ $inc: {
"comments.$.body": body,
"comments.$.perfil": theUser.perfil,
}},
false,
true,
);
或者我认为最好的选择是使用文档之间的关系。创建另一个名为 Comment
的文档并将所有相关评论保存在那里。在这种情况下,您将能够使用 .save()
和其他提供的方法。