我遇到了一些使用mongoose在express.js中转换ObjectId的问题。
在我的路线中,我已经尝试过这两种类型转换,以及直接使用req.params.id。似乎什么都不起作用。我百分之百确定id是正确的。我已经尝试创建一个新的帖子,并多次直接复制id。
你知道为什么我的ObjectId不被识别吗?
我的架构:
let PostSchema = new Schema({
_id: {type: mongoose.Schema.Types.ObjectId, auto: true},
title: String,
author: String,
date: { type: Date, default: Date.now()},
body: String,
comments: [CommentSchema],
upvotes: Number,
downvotes: Number,
});我的路线:
app.post('/api/post/:id/comment', (req, res) => {
let comment = new PostComment({
author: req.body.author,
body: req.body.body,
date: req.body.date,
upvotes: 0,
downvotes: 0,
})
const id = mongoose.ObjectId.cast(req.params.id)
Post.findOneAndUpdate(
{_id: id},
{ $push: {comments: comment}}
)
.then(result => {
if(!result) {
res.sendStatus(404).send({
success: 'false',
message: 'Comment not added',
});
} else {
res.status(200).json(result);
}
})
.catch(err => console.log(err));
});错误消息:
Cast to ObjectId failed for value "{ id: \'5cc3632db9e2405960e3ed0e\' }" at path "_id" for model "Post"存在相同问题的额外路由:
// get single post by id
app.get("/api/post/:id", (req, res) => {
const id = req.params;
Post.findById(id)
.exec()
.then(result => {
if(!result) {
res.sendStatus(404).send({
success: 'false',
message: 'No post found',
});
} else {
res.status(200).json(result);
}
})
.catch(err => console.log(err));
});发布于 2019-04-27 04:25:37
似乎只要你发帖,你就会自己找到答案,所以就这样吧。此函数将有效地将字符串转换为ObjectId:mongoose.Types.ObjectId(req.params.id);
https://stackoverflow.com/questions/55874417
复制相似问题