简体   繁体   English

在哪里可以找到我的代码中模型“ Item”的路径“ _id”的值“ create”的Cast to ObjectId的源失败

[英]Where can I find the source of Cast to ObjectId failed for value “create” at path “_id” for model “Item” in my code

I'm creating an inventory App for the odin project's Nodejs project whilist following the MDN's Express.js tutorial. 我在MDN的Express.js教程之后为odin项目的Nodejs项目向导创建了清单应用程序。 I can delete items, update items and read items, but when I want to create items I get the error mentioned (Cast to ObjectId failed for value "create" at path "_id" for model "Items"). 我可以删除项目,更新项目和读取项目,但是当我要创建项目时,会出现错误(对于模型“项目”,在路径“ _id”的值“创建”对ObjectId的转换失败)。

I've looked through all my code and when I tried to replace what was in "items_create_get" the error never changed which lead me to believe that it is not the issue. 我仔细阅读了所有代码,尝试替换“ items_create_get”中的内容时,错误从未改变,这使我认为这不是问题。

//itemsController.js:
var Items = require("../models/items");
var async = require("async");
const { body, validationResult } = require("express-validator/check");
const { sanitizeBody } = require("express-validator/filter");

exports.items_create_post = [
// Convert the category to an array.
(req, res, next) => {
if (!(req.body.category instanceof Array)) {
    if (typeof req.body.category === "undefined") 
        req.body.category = [];
    else req.body.category = new Array(req.body.category);
}
    next();
},

// Handle items create on POST.
exports.items_create_post = [
   // Convert the category to an array.
    (req, res, next) => {
        if (!(req.body.category instanceof Array)) {
            if (typeof req.body.category === "undefined") 
                req.body.category = [];
            else req.body.category = new Array(req.body.category);
        }
        next();
   },

// Validate fields.
body("name", "Name must not be empty.")
.isLength({ min: 1 })
.trim(),
body("description", "Description must not be empty.")
.isLength({ min: 1 })
.trim(),
body("price", "Price must not be empty.")
.isLength({ min: 1 })
.trim(),
body("num_in_stock", "Number in stock must not be empty")
.isLength({ min: 1 })
.trim(),

// Sanitize fields.
sanitizeBody("*").escape(),
sanitizeBody("category.*").escape(),
// Process request after validation and sanitization.
(req, res, next) => {
  // Extract the validation errors from a request.
  const errors = validationResult(req);

  // Create a Items object with escaped and trimmed data.
  var items = new Items({
    name: req.body.name,
    description: req.body.description,
    category: req.body.category,
    price: req.body.price,
    num_in_stock: req.body.num_in_stock
  });

  if (!errors.isEmpty()) {
    /* There are errors. Render form again with sanitized values/error messages.*/

  // Get all categories for form.
  async.parallel(
    {
      category: function(callback) {
        Category.find(callback);
      }
    },
    function(err, results) {
      if (err) {
        return next(err);
      }

      res.render("items_form", {
        title: "Create Item",
        category: results.category,
        items: items,
        errors: errors.array()
      });
    }
  );
  return;
} else {
  // Data from form is valid. Save book.
  items.save(function(err) {
    if (err) {
      return next(err);
    }
    // Successful - redirect to new items record.
    res.redirect(items.url);
  });
}
}
];

//items.js(Model):
var mongoose = require('mongoose');

var Schema = mongoose.Schema;

var ItemsSchema = new Schema ({
name: {type: String, required: true, max: 100},
description: {type: String, required: true},
category: {type: Schema.Types.ObjectId, ref: 'Category', required: true},
price: {type: String, required: true},
num_in_stock: {type: String, required: true}
})

ItemsSchema.virtual('url').get(function() {
     return '/catalog/items/' + this._id
});

module.exports = mongoose.model('Items', ItemsSchema);

//catalog.js (Router):

router.get('/items/create', items_controller.items_create_get);
router.post('/items/create', items_controller.items_create_post);

//items_form.pug(views):

extends layout

block content
    h1= title

    form(method='POST' action='')
        div.form-group
            label(for='name') Name:
            input#name.form-control(type='text', placeholder='Name of item' name='name' required='true' value=(undefined===items ? '' : items.name) )
        div.form-group
             label(for='description') Description:
             input#description.form-control(type='textarea', placeholder='Enter Description' name='description' value=(undefined===items ? '' : items.description) required='true' )
        div.form-group
            label(for='category') Category:
            input#category.form-control(type='text', placeholder='Consumable, Tools or Accessories' name='category' value=(undefined===items ? '' : items.category.name) required='true' )
        div.form-group
            label(for='price') Price:
            input#price.form-control(type='text', placeholder='Price: e.g. 20$' name='price' value=(undefined===items ? '' : items.price) required='true')
        div.form-group
            label(for='num_in_stock') Number in Stock:
            input#num_in_stock.form-control(type='text', placeholder='num in stock: e.g. 2' name='num_in_stock' value=(undefined===items ? '' : items.num_in_stock) required='true') 
        button.btn.btn-primary(type='submit') Submit 

    if errors 
        ul
            for error in errors
                li!= error.msg

//Edit: catalog.js (Router):
// GET catalog home page.
router.get('/', items_controller.index);
// GET request for one Item.
router.get('/items/:id', items_controller.items_detail);
// GET request for list of all Item.
router.get('/items', items_controller.items_list);
router.get('/items/create', items_controller.items_create_get);
router.post('/items/create', items_controller.items_create_post);
// GET request to delete Item.
router.get('/items/:id/delete', items_controller.items_delete_get);
// POST request to delete Item.
router.post('/items/:id/delete',
items_controller.items_delete_post);
// GET request to update Item.
router.get('/items/:id/update', items_controller.items_update_get);
// POST request to update Item.
router.post('/items/:id/update',
items_controller.items_update_post);

this problem is also in my category model as well... 这个问题也在我的类别模型中...

the output screen is fine and all the other CRUD views work other than the create controller... Maybe it's worth mentioning that when I update my items my items_form.js works perfectly! 输出屏幕很好,并且所有其他CRUD视图都可以使用create控制器以外的其他功能。也许值得一提的是,当我更新项目时,items_form.js可以完美运行! */ * /

The problem is with your virtual in schema, try changing it to: 问题出在您的虚拟架构中,请尝试将其更改为:

ItemsSchema.virtual('url').get(function() {
     return '/catalog/items/' + this._id.toString()
});

That is because the _id is of type ObjectId and you are trying to concat it with string. 这是因为_id的类型为ObjectId,并且您尝试将其与字符串连接。

Hope this helps :) 希望这可以帮助 :)

Because you putting: 因为您放:

router.get('/items/:id', items_controller.items_detail);

Before: 之前:

router.get('/items/create', items_controller.items_create_get);

So when you call /items/create , the router will point to items_controller.items_detail , not items_controller.items_create_get and get create as the param id . 因此,当您调用/items/create ,路由器将指向items_controller.items_detail ,而不是items_controller.items_create_get并获取create作为参数id

Change your router to put /items/:id after /items/create may solve your problem. 将路由器更改为在/items/create之后放置/items/:id可能会解决您的问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在模型的路径“ _id”处将值“”投射到ObjectId失败 - Cast to ObjectId failed for value “ ” at path “_id” for model 消息:'Cast to ObjectId 因模型“item”路径“_id”处的值“xxxxxx”而失败',名称:'CastError',模型:Model { item } } - message: 'Cast to ObjectId failed for value "xxxxxx " at path "_id" for model "item"', name: 'CastError', model: Model { item } } 如何修复 model “Item” 错误的 “CastError: Cast to ObjectId failed for value “Item 1.1” at path “_id”? - How to fix “CastError: Cast to ObjectId failed for value ”Item 1.1“ at path ”_id“ for model ”Item“” error? ZCCADCDEDB567ABAE643E15DCF0974E503Z:CastError:对于 model “”的路径“_id”处的值“未定义”,转换为 ObjectId 失败 - Mongoose: CastError: Cast to ObjectId failed for value “undefined” at path “_id” for model “” CastError:对于 model“用户”的路径“_id”处的值“未定义”,转换为 ObjectId 失败 - CastError: Cast to ObjectId failed for value "undefined" at path "_id" for model "User" Mongoose:CastError:对于模型“”的路径“_id”中的值“”,CastError:Cast to ObjectId失败 - Mongoose: CastError: Cast to ObjectId failed for value "" at path "_id" for model "" 对于 model“用户”的路径“_id”中的值“未定义”,转换为 ObjectId 失败 - Cast to ObjectId failed for value “undefined” at path “_id” for model “User” 模型“ Post”的路径“ _id”的值“ undefined”的铸造到ObjectId失败 - Cast to ObjectId failed for value “undefined” at path “_id” for model “Post”" CastError:对于模型“customer”的路径“_id”中的值“customers”,Cast to ObjectId失败 - CastError: Cast to ObjectId failed for value "customers" at path "_id" for model "customer" 在路径“ _id”的值“ 0”强制转换为ObjectId - Cast to ObjectId failed for value “0” at path “_id”
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM