猫鼬转换错误:模型"Post"路径 "_id" 处的值 "undefined" 强制转换为对象 ID 失败



我在一个MEAN堆栈项目中工作,用户可以添加帖子,编辑和删除它们。但执行所需的方法后,帖子没有被删除,我面临一个错误。我是MEAN stack的新手。

posts.service.ts

getPosts() {
this.http.get<{ message: string, posts: any }>('http://localhost:3300/api/posts')
.pipe(
map((postData) => {
return postData.posts.map(post=>{
return{
title: post.title,
content: post.content,
id: post._id
}
})
}))
.subscribe((transformedPosts)=>{
this.posts = transformedPosts; 
this.postsUpdated.next([...this.posts])  //updating the posts so that it is available to the rest of the app
})
}
getUpdatedPostsListener(){
return this.postsUpdated.asObservable()
}

addPosts(id: any, title: string, content: string) {
const post: PostModel = {
id: id,
title: title,
content: content
}
this.http.post<{ message: string }>('http://localhost:3300/api/posts', post).subscribe((responseData)=>{
console.log(responseData.message);
})
this.posts.push(post);
this.postsUpdated.next([...this.posts]);
}
deletePosts(postId: string){
this.http.delete('http://localhost:3300/api/posts/' + postId)
.subscribe(()=>{
const updatedPosts = this.posts.filter(post => post.id! == postId);
this.posts = updatedPosts;
this.postsUpdated.next([...this.posts]);
})
}

app.js

app.delete('/api/posts/:id', (req, res, next) => {
Post.deleteOne({ _id: req.params.id }).then(result => {
console.log(result);
res.status(200).json({
message: 'Post deleted successfully!'
})
})
.catch(err => {
console.log('error: ', err);
})

})

posts.components.ts

onDelete(postId: string){
this.postsService.deletePosts(postId);
}

posts.component.html

<mat-action-row>
<button color="primary" mat-raised-button>Edit</button>
<button color="warn" mat-raised-button (click)="onDelete(post.id)">Delete</button>
</mat-action-row>

post-models.js(用于后端)

const mongoose = require('mongoose');
const postSchema = mongoose.Schema({
title: { type: String, required: true },
content: { type: String, required: true }
})

module.exports = mongoose.model('Post', postSchema)

这是我每次尝试删除任何帖子时都会遇到的错误:-

错误:CastError:转换为objecd失败的值"undefined"在路径"_id"for model "Post"在model.Query.exec (E:AngularKUSpacenode_modulesmongooselibquery.js:4358:21)在model.Query.Query.then (E:AngularKUSpacenode_modulesmongooselibquery.js:4452:15)E: 角 KUSpace 端 app.js: 48:43在层。handle [as handle_request] (E:AngularKUSpacenode_modulesexpresslibrouterlayer.js:95:5)at next (E:AngularKUSpacenode_modulesexpresslibrouter Route. js:137:13)
at Route. js调度(E: 角 KUSpace node_modules lib 路由器 route.js表达:112:3)在层。handle [as handle_request] (E:AngularKUSpacenode_modulesexpresslibrouterlayer.js:95:5)E: 角 KUSpace node_modules 表达 lib 路由器 index.js: 281:22AngularKUSpacenode_modulesexpresslibrouterindex.js:354:14@ param (E:AngularKUSpacenode_modulesexpresslibrouterindex.js:365:14)在函数。process_params (E: 角 KUSpace node_modules lib 路由器 index.js表达:410:3)at next (E:AngularKUSpacenode_modulesexpresslibrouterindex.js:275:10)
at E:AngularKUSpacebackendapp.js:22:5在层。handle [as handle_request] (E:AngularKUSpacenode_modulesexpresslibrouterlayer.js:95:5)@ trim_prefix (E:AngularKUSpacenode_modulesexpresslibrouterindex.js:317:13)at E:AngularKUSpacenode_modulesexpresslibrouterindex.js:284:7 {
messageFormat: undefined, stringValue: '"undefined"', kind:'ObjectId',值:'undefined',路径:'_id',原因:错误:参数必须是一个12字节的字符串或字符串24个十六进制字符at new ObjectID (E:AngularKUSpacenode_modulesbsonlibbson ObjectID .js:59:11)@ castObjectId (E:AngularKUSpacenode_modulesmongooselibcastobjectid.js:25:12)ObjectId。铸造(E: 角 KUSpace node_modules 猫鼬 lib objectid.js模式:279:12)/////////////////在ObjectId.SchemaType。_castForQuery (E: 角 KUSpace node_modules 猫鼬 lib schematype.js: 1523:15)在objecd . schematype. castforquery (E:AngularKUSpacenode_modulesmongooselibschematype.js:1513:15)在objecd . schematype. castforquerywrapper (E:AngularKUSpacenode_modulesmongooselibschematype.js:1490:20)at cast (E:AngularKUSpacenode_modulesmongooselibcast.js:331:32)
at model.Query.Query.cast (E:AngularKUSpacenode_modulesmongooselibquery.js:4763:12)在model.Query.Query。_castConditions (E: 角 KUSpace node_modules 猫鼬 lib query.js: 1841:10)在model.Query。(E: 角 KUSpace node_modules 猫鼬 lib query.js: 2722:8)在model.Query。_wrapdthunk [as _deleteOne] (E:AngularKUSpacenode_modulesmongooselibhelpersquerywrapThunk.js:16:8)E: 角 KUSpace node_modules kareem index.js: 370:33at processTicksAndRejections (internal/process/task_queues.js:75:11)}

简短回答:

如果您不想处理ObjectId以及ObjectIdStringid_id之间的转换,

您可以使用_id字段后端和前端。此外,要将其保存在后端为String,请在模式中添加以下行:

_id: { type: String, required: true }

现在,当你创建一个新的帖子时,你可以这样写:

const post: PostModel = {
_id: _id,
title: title,
content: content
}

然后你可以使用bson生成新的ObjectId传递给后端。

import { ObjectID } from 'bson';
{ _id: new ObjectID().toHexString() }

在更改post.service.ts中的AddPosts方法后,问题解决了

post.service.ts

addPosts(title: string, content: string) {
const post: PostModel = {
id: null,
title: title,
content: content
}
this.http.post<{ message: string , postId: string }>('http://localhost:3300/api/posts', post).subscribe((responseData)=>{
console.log(responseData.message);
post.id = responseData.postId;
this.posts.push(post);
this.postsUpdated.next([...this.posts]);
})

}

相关内容

  • 没有找到相关文章