Mongodb findOneAndUpdate返回未定义
当这条路线被执行时,我的承诺是返回未定义的。我知道我有正确的Post id,因为我已经检查了DB文档本身。我不明白为什么如果它找到文档,它甚至会返回未定义的文档。提前谢谢Mongodb findOneAndUpdate返回未定义,mongodb,mongoose,mongodb-query,Mongodb,Mongoose,Mongodb Query,当这条路线被执行时,我的承诺是返回未定义的。我知道我有正确的Post id,因为我已经检查了DB文档本身。我不明白为什么如果它找到文档,它甚至会返回未定义的文档。提前谢谢 router.post( "/comment/:id", passport.authenticate("jwt", { session: false }), (req, res) => { // Check Validation new Comment(
router.post(
"/comment/:id",
passport.authenticate("jwt", { session: false }),
(req, res) => {
// Check Validation
new Comment({
user: req.user._id,
text: req.body.text,
})
.save()
.then(comment => {
Post.findOneAndUpdate(
{ _id: req.params.id },
{ $push: { comments: comment._id } },
{ new: true }
);
})
.then(post => {
console.log(post);
res.json(post);
})
.catch(err => {
console.log(err);
res.status(404).json({ postnotfound: "No post found" });
});
}
);
后架构
const PostSchema = new Schema({
user: {
type: Schema.Types.ObjectId,
ref: "users"
},
text: {
type: String,
required: true
},
likes: [
{
user: {
type: Schema.Types.ObjectId,
ref: "users"
}
}
],
comments: [
{
type: Schema.Types.ObjectId,
ref: "comment",
date: {
type: Date,
default: Date.now
}
}
],
date: {
type: Date,
default: Date.now
}
});
module.exports = Post = mongoose.model("post", PostSchema);
啊哈,所以我把我的
。然后
从我的帖子中分离出来。findOneAndUpdate
,有意义=]
router.post(
"/comment/:id",
passport.authenticate("jwt", { session: false }),
(req, res) => {
// Check Validation
new Comment({
user: req.user._id,
text: req.body.text
})
.save()
.then(comment => {
Post.findOneAndUpdate(
{ _id: req.params.id },
{ $push: { comments: comment._id } },
{ new: true }
)
.then(post => { <---
console.log(post);
res.json(post);
})
.catch(err => {
console.log(err);
res.status(404).json({ postnotfound: "No post found" });
});
});
}
);
router.post(
“/comment/:id”,
passport.authenticate(“jwt”{session:false}),
(请求、回复)=>{
//检查验证
新评论({
用户:请求用户。\u id,
文本:req.body.text
})
.save()
。然后(评论=>{
Post.findOneAndUpdate(
{{u id:req.params.id},
{$push:{comments:comment.\u id}},
{新:正确}
)
.then(post=>{{
控制台日志(err);
json({postnotfound:“未找到post”});
});
});
}
);
Aha,所以我有了我的。然后
从我的帖子中分离出来。findOneAndUpdate
,有意义=]
router.post(
"/comment/:id",
passport.authenticate("jwt", { session: false }),
(req, res) => {
// Check Validation
new Comment({
user: req.user._id,
text: req.body.text
})
.save()
.then(comment => {
Post.findOneAndUpdate(
{ _id: req.params.id },
{ $push: { comments: comment._id } },
{ new: true }
)
.then(post => { <---
console.log(post);
res.json(post);
})
.catch(err => {
console.log(err);
res.status(404).json({ postnotfound: "No post found" });
});
});
}
);
router.post(
“/comment/:id”,
passport.authenticate(“jwt”{session:false}),
(请求、回复)=>{
//检查验证
新评论({
用户:请求用户。\u id,
文本:req.body.text
})
.save()
。然后(评论=>{
Post.findOneAndUpdate(
{{u id:req.params.id},
{$push:{comments:comment.\u id}},
{新:正确}
)
.then(post=>{{
控制台日志(err);
json({postnotfound:“未找到post”});
});
});
}
);