这是我遇到的两个错误。
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
我的索引.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>
我的主文件.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和Javascript的新手,我正在尝试构建一些东西作为一种学习方式。 但是我遇到了一个错误,让我尝试了几个小时都没有成功。 请我需要帮助来修复此错误。
我试图保持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');
});
});