javascript - 如何修复“CastError: Cast to ObjectId failed for value "Item 1.1" at path "_id" for model "Item"" 错误?
问题描述
我正在做一个项目,我需要在另一个文档内的数组中添加一个文档,但每次我尝试时都会收到此错误:
CastError: Cast to ObjectId failed for value "Item 1.1" at path "_id" for model "Item"
at model.Query.exec (C:\Users\Children\Desktop\Web Projects\App Line Planner\node_modules\mongoose\lib\query.js:4361:21)
at _update (C:\Users\Children\Desktop\Web Projects\App Line Planner\node_modules\mongoose\lib\query.js:4213:11)
at model.Query.Query.updateOne (C:\Users\Children\Desktop\Web Projects\App Line Planner\node_modules\mongoose\lib\query.js:4112:10)
at _update (C:\Users\Children\Desktop\Web Projects\App Line Planner\node_modules\mongoose\lib\model.js:3780:16)
at Function.updateOne (C:\Users\Children\Desktop\Web Projects\App Line Planner\node_modules\mongoose\lib\model.js:3716:10)
at C:\Users\Children\Desktop\Web Projects\App Line Planner\main.js:77:22
at C:\Users\Children\Desktop\Web Projects\App Line Planner\node_modules\mongoose\lib\model.js:4866:16
at C:\Users\Children\Desktop\Web Projects\App Line Planner\node_modules\mongoose\lib\model.js:4866:16
at C:\Users\Children\Desktop\Web Projects\App Line Planner\node_modules\mongoose\lib\helpers\promiseOrCallback.js:24:16
at C:\Users\Children\Desktop\Web Projects\App Line Planner\node_modules\mongoose\lib\model.js:4889:21
at C:\Users\Children\Desktop\Web Projects\App Line Planner\node_modules\mongoose\lib\query.js:4400:11
at C:\Users\Children\Desktop\Web Projects\App Line Planner\node_modules\kareem\index.js:136:16
at processTicksAndRejections (internal/process/task_queues.js:79:11) {
messageFormat: undefined,
stringValue: '"Item 1.1"',
kind: 'ObjectId',
value: 'Item 1.1',
path: '_id',
reason: Error: Argument passed in must be a single String of 12 bytes or a string of 24 hex characters
at new ObjectID (C:\Users\Children\Desktop\Web Projects\App Line Planner\node_modules\bson\lib\bson\objectid.js:59:11)
at castObjectId (C:\Users\Children\Desktop\Web Projects\App Line Planner\node_modules\mongoose\lib\cast\objectid.js:25:12)
at ObjectId.cast (C:\Users\Children\Desktop\Web Projects\App Line Planner\node_modules\mongoose\lib\schema\objectid.js:279:12)
at ObjectId.SchemaType.applySetters (C:\Users\Children\Desktop\Web Projects\App Line Planner\node_modules\mongoose\lib\schematype.js:1091:12)
at ObjectId.SchemaType._castForQuery (C:\Users\Children\Desktop\Web Projects\App Line Planner\node_modules\mongoose\lib\schematype.js:1526:15)
at ObjectId.SchemaType.castForQuery (C:\Users\Children\Desktop\Web Projects\App Line Planner\node_modules\mongoose\lib\schematype.js:1516:15)
at ObjectId.SchemaType.castForQueryWrapper (C:\Users\Children\Desktop\Web Projects\App Line Planner\node_modules\mongoose\lib\schematype.js:1493:20)
at cast (C:\Users\Children\Desktop\Web Projects\App Line Planner\node_modules\mongoose\lib\cast.js:331:32)
at model.Query.Query.cast (C:\Users\Children\Desktop\Web Projects\App Line Planner\node_modules\mongoose\lib\query.js:4766:12)
at model.Query.Query._castConditions (C:\Users\Children\Desktop\Web Projects\App Line Planner\node_modules\mongoose\lib\query.js:1843:10)
at model.Query._updateThunk (C:\Users\Children\Desktop\Web Projects\App Line Planner\node_modules\mongoose\lib\query.js:3710:8)
at model.Query.<anonymous> (C:\Users\Children\Desktop\Web Projects\App Line Planner\node_modules\mongoose\lib\query.js:3842:23)
at model.Query._wrappedThunk [as _updateOne] (C:\Users\Children\Desktop\Web Projects\App Line Planner\node_modules\mongoose\lib\helpers\query\wrapThunk.js:16:8)
at C:\Users\Children\Desktop\Web Projects\App Line Planner\node_modules\kareem\index.js:370:33
at processTicksAndRejections (internal/process/task_queues.js:79:11)
我已经尝试修复它,但仍然无法正常工作。这是问题所在:
app.post('/addinitem', function (req, res) {
tabb += 1;
tex = req.body.addtoitem;
const item2 = new Item({
name: namee,
initem: [],
text: tex,
tab: tabb
});
Item.find({ name: namee }, function (err, foundITems) {
if (err) {
console.log(err);
} else {
if (foundITems) {
var itemid = req.body.addtoitem;
console.log(itemid);
Item.updateOne({ _id: itemid }, { $push: { initem: item2 } }, function (err) {
if (err) {
console.log(err);
}
});
console.log("added initem");
}
}
});
});
这是完整的代码:
const express = require('express');
const bodyParser = require('body-parser');
const ejs = require('ejs');
const mongoose = require('mongoose');
mongoose.connect("mongodb://localhost:27017/appline", { useUnifiedTopology: true }, { useNewUrlParser: true });
const itemSchema = {
name: String,
initem: Array,
text: String,
tab: Number
}
const Item = mongoose.model("Item", itemSchema);
const app = express();
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static('public'));
const items = [];
const tabs = [];
var foundItemList1;
var namee = "";
var tabb = 0;
app.get('/login', function (req, res) {
res.render('login');
});
app.post('/login', function (req, res) {
namee = req.body.name;
res.redirect('/');
})
app.get('/', function (req, res) {
if (namee == "") {
res.redirect('/login');
} else {
Item.find({ name: namee }, function (err, foundItemList) {
if (err) {
console.log(err);
} else if (foundItemList) {
console.log(namee);
console.log("Found ITems: " + foundItemList);
for (var i = 0; i < foundItemList.length; i++) {
foundItemList1 = foundItemList[i].initem;
}
res.render('main', { item: foundItemList, foundItems: foundItemList1 });
}
});
}
});
app.post('/addinitem', function (req, res) {
tabb += 1;
tex = req.body.addtoitem;
const item2 = new Item({
name: namee,
initem: [],
text: tex,
tab: tabb
});
Item.find({ name: namee }, function (err, foundITems) {
if (err) {
console.log(err);
} else {
if (foundITems) {
var itemid = req.body.addtoitem;
console.log(itemid);
Item.updateOne({ _id: itemid }, { $push: { initem: item2 } }, function (err) {
if (err) {
console.log(err);
}
});
console.log("added initem");
}
}
});
});
app.post('/add', function (req, res) {
const item = req.body.newItem;
console.log(item);
items.push(item);
const item1 = new Item({
name: namee,
initem: [],
text: item
});
item1.save();
console.log(item1);
res.redirect('/');
});
app.listen(3000, function () {
console.log('Server started on port 3000.');
});
这是html中的错误位置:
<div class="card shadow-sm w-75 mx-auto py-1 px-2 my-1 containe h-auto"
style=" height: 40px; vertical-align: middle;">
<div class="row-cols-3" style="height: auto; vertical-align: middle; display: flex; padding: 10px;">
<div style=" height: 25px; float: left; display: flex;" class="my-auto w-75">
<input type="checkbox" name="checked" id="" class="" style="width: 20px; height: 20px; flo">
<p class="text-primary mx-3">
<%= items.text %>
</p>
</div>
<div style="width: fit-content; height: 25px;" class="my-auto btn-group mx-5">
<button type="submit" class="btn btn-outline-danger col mx-auto"
style="width: 25px; height: 25px; border-radius: 0; margin-right: 0px; padding: 0; font-size: large;">-</button>
<button type="submit" class="btn btn-outline-primary col mx-auto"
style="width: 25px; margin-left: 2px; height: 25px; border-radius: 0; border-top-right-radius: 2px; border-bottom-right-radius: 2px; margin-left: 0px; padding: 0; font-size: large;"
data-bs-toggle="collapse" href="#collapseExample" role="button" aria-expanded="false"
aria-controls="collapseExample">+</button>
</div>
</div>
<div class="collapse" id="collapseExample">
<form action="/addinitem" method="POST">
<div class="card" style="display: block;">
<button type="submit" class="btn btn-outline-primary w-25">+</button>
<input type="text" name="addtoitem" id="" class="form-control w-75 float-end">
</div>
</form>
</div>
</div>
解决方案
将_id转换成objectID,可以这样。
import mongoose from "mongoose";
const { ObjectId } = mongoose.Types;
_id: ObjectId(itemid )
推荐阅读
- c# - 如何使用动态查询获取特定属性的总和
- python - 我在通过 pip 安装 flask_cors 时遇到问题
- excel - 形成构建树视图结构的循环
- iis - 将带有扩展名的错误网址重定向到非扩展名
- ruby - 如何在 Ruby 中手动缩短字母?没有 sort 或 sort_by 方法
- javascript - 带有折线图和条形图的 Chart.js - 尽管显示了最大值,但条形图未呈现
- css - Angular 7 模板没有填满整个页面
- javascript - 使用 bookmarks.create 在 Firefox 中添加书签时获取“浏览器未定义”
- c# - 使用 c# 在 cassandra 中批量插入
- algorithm - 如何找到以下递归代码的时间复杂度?