这里有两个错误。
MongooseError [CastError]: Cast to ObjectId failed for value "{item._id}" at path "_id" for model "Post"
第二个
stringValue: '"{item._id}"',
kind: 'ObjectId',
value: '{item._id}',
path: '_id',
reason: Error: Argument passed in must be a single String of 12 bytes or a string of 24 hex characters
我的Index.js
mongoose.connect("mongodb://localhost:27017/postcomment", {useUnifiedTopology: true, useNewUrlParser: true, useCreateIndex: true });
var Schema = mongoose.Schema;
var PostSchema = new Schema({
title: String,
content: String,
author: String
});
var Post = mongoose.model('Post', PostSchema);
router.delete( '/post/:id', function( req, res ){
let query = {_id:req.params.id}
Post.deleteOne(query, function(err) {
if(err){
console.log(err);
}
res.send('Success');
});
});
我的删除按钮
<a class="delete-article" href="#" data-id="{item._id}">Delete</a>
我的main.js文件
$(document).ready(function() {
$('.delete-article').on('click', function(e) {
const $target = $(e.target);
const id = $target.attr('data-id');
$.ajax({
type: 'DELETE',
url: '/post/'+id,
success: function(response) {
alert('Deleting Post');
window.location.href='/';
},
error: function(err){
console.log(err);
}
});
});
[![This is a snapshot of the error message][1]][1]});
我的View
<% items.forEach(item => { %>
<ul>
<h1><%=item.title%></h1>
<li><%= item.content %></li>
<li><%= item.author %></li>
<a class="delete-article" href="#" data-id="{item.id}">Delete</a>
</ul>
<% });%>
<li><a href="/newpost">Add New Post</a></li>
我是Node和Java的新手,我正在尝试构建一些学习方法。但是我遇到了一个错误,这让我尝试了数小时都没有成功。请我需要帮助来解决此错误。
我正在尝试将其保留为CRUD
,所以我正在使用delete
从数据库中删除帖子。我遇到的错误是指ObjectId
和passing a single string of 12
咬伤,我已经尝试过但没有成功。请我将不胜感激的任何修复此问题,并解释,以帮助我理解它。
谢谢你们
您没有传递文档ID,但您传递了{item._id},尝试修复您的data-id="{item._id}"
以传递实际的_id。在路由器上检查您从浏览器发送的id参数
router.delete( '/post/:id', function( req, res ){
// check the id if it is valid
console.log(req.params.id)
let query = {_id:req.params.id}
Post.deleteOne(query, function(err) {
if(err){
console.log(err);
}
res.send('Success');
});
});
您正在使用什么模板引擎?
您可以尝试一下,也许您从前端传递的ID并非ID格式
const mongoose = require('mongoose');
const ObjectId = mongoose.Types.ObjectId;
router.delete( '/post/:id', function( req, res ){
// check the id if it is valid
console.log(req.params.id)
let query = {_id:new ObjectId(req.params.id)}
Post.deleteOne(query, function(err) {
if(err){
console.log(err);
}
res.send('Success');
});
});