我有一個簡單的快速應用程式,可以將評論插入到帖子中,問題是從來沒有插入評論,但通過郵遞員發布時不會顯示任何錯誤,它會正確回傳帖子但沒有評論。試試看:這個和這個但似乎不起作用
這是我的架構
interface PostAttrs {
userid: mongoose.Schema.Types.ObjectId;
username: string;
date: Date;
text: string;
image: string;
comments: Array<any>;
likes?: number;
}
const postSchema = new Schema<PostAttrs>({
userid: {
type: mongoose.Schema.Types.ObjectId,
required: true,
},
username: {
type: String,
required: true,
},
date: {
type: Date,
required: true,
},
text: {
type: String,
required: true,
},
image: {
type: String,
required: false,
},
comments: [
{
required: false,
date: {
type: String,
required: true,
},
user: {
type: Schema.Types.ObjectId,
ref: 'User',
required: true,
},
text: {
type: String,
required: true,
},
},
],
likes: {
type: Number,
required: true,
},
});
和 API 路線
export const createComment = async (req: Request, res: Response) => {
try {
const postId = req.params.postId;
const userId = req.params.userId;
const comment = req.body.comment;
var commentObj = {
date: new Date(),
userId: userId,
text: comment
};
await Post.findOneAndUpdate(
{ _id: postId },
{ new: true },
{$push: {
comments: { commentObj }
}},
(err: any, doc: any) => {
if (err) {
console.log("Something wrong when updating data!");
}
console.log(doc);
return res.status(200).send(doc);
}
);
} catch (error) { }
}
我的代碼有什么問題?
uj5u.com熱心網友回復:
已解決:問題是 findOneAndUpdate() 陳述句中引數的順序,首先是搜索條件,其次是要更新的值,最后是陳述句。所以我不得不改變這個
await Post.findOneAndUpdate(
{ _id: postId },
{ new: true },
{$push: {
comments: { commentObj }
}},
(err: any, doc: any) => {
if (err) {
console.log("Something wrong when updating data!");
}
console.log(doc);
return res.status(200).send(doc);
});
到
await Post.findOneAndUpdate(
{ _id: postId },
{$push: {
comments: { commentObj }
}},
{ new: true },
(err: any, doc: any) => {
if (err) {
console.log("Something wrong when updating data!");
}
console.log(doc);
return res.status(200).send(doc);
});
uj5u.com熱心網友回復:
當將“await”與 Mongoose 的方法(如 findOneAnd...)一起使用時,除非您明確這樣做,否則該方法不會運行。
嘗試:
await Post.findOneAndUpdate(......).exec();
此外,當使用 await 關鍵字時,您可以重構和洗掉回呼
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/370564.html
