MongooseError [CastError]:模型“List”的路径“_id”的值“ name:'C'”转换为 ObjectId 失败

Posted

技术标签:

【中文标题】MongooseError [CastError]:模型“List”的路径“_id”的值“ name:\'C\'”转换为 ObjectId 失败【英文标题】:MongooseError [CastError]: Cast to ObjectId failed for value " name: 'C' " at path "_id" for model "List"MongooseError [CastError]:模型“List”的路径“_id”的值“ name:'C'”转换为 ObjectId 失败 【发布时间】:2021-06-19 04:40:47 【问题描述】:

使用 mongoose 和 ejs 做应用程序

我试图降低不同版本的猫鼬来解决问题。还尝试 console.log 问题,我了解到列表集合是通过 .save() 方法收集数据,而项目集合无法保存。这是在 findList of app.post('/' ) 正在给出 null 的输出,这给出了无法推送 null 的错误。 MongooseError [CastError]: Cast to ObjectId failed for value " name: 'C' " at path "_id" for model "List" 这个错误是在点击复选框后产生的。 应该删除自定义 url 的项目集合中的项目。在编码时,它工作了一段时间,然后由于一些代码中断而停止工作。

Package.json 文件:


  "name": "todolist-v1",
  "version": "1.0.0",
  "description": "To do list app by EJS, backend API, MongoDB database",
  "main": "app.js",
  "scripts": 
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node app.js"
  ,
  "author": "Clinto Abraham Ayamkudiyil",
  "license": "ISC",
  "dependencies": 
    "body-parser": "^1.18.3",
    "ejs": "^2.6.1",
    "express": "^4.17.1",
    "lodash": "^4.17.21",
    "mongoose": "^5.12.1"
  


更新了 mongoose 的 npm 版本,hyper 中的错误:

CastError: Cast to ObjectId failed for value " name: 'Delete' " at path "_id" for model "List"
    at model.Query.exec (E:\Full-Stack-Developer\EJS\putting all together\toDoList\node_modules\mongoose\lib\query.js:4361:21)
    at model.Query.Query.findOneAndRemove (E:\Full-Stack-Developer\EJS\putting all together\toDoList\node_modules\mongoose\lib\query.js:3108:8)
    at Function.Model.findOneAndRemove (E:\Full-Stack-Developer\EJS\putting all together\toDoList\node_modules\mongoose\lib\model.js:2909:13)
    at Function.Model.findByIdAndRemove (E:\Full-Stack-Developer\EJS\putting all together\toDoList\node_modules\mongoose\lib\model.js:2961:15)
    at E:\Full-Stack-Developer\EJS\putting all together\toDoList\app.js:132:10
    at Layer.handle [as handle_request] (E:\Full-Stack-Developer\EJS\putting all together\toDoList\node_modules\express\lib\router\layer.js:95:5)
    at next (E:\Full-Stack-Developer\EJS\putting all together\toDoList\node_modules\express\lib\router\route.js:137:13)
    at Route.dispatch (E:\Full-Stack-Developer\EJS\putting all together\toDoList\node_modules\express\lib\router\route.js:112:3)
    at Layer.handle [as handle_request] (E:\Full-Stack-Developer\EJS\putting all together\toDoList\node_modules\express\lib\router\layer.js:95:5)
    at E:\Full-Stack-Developer\EJS\putting all together\toDoList\node_modules\express\lib\router\index.js:281:22
    at Function.process_params (E:\Full-Stack-Developer\EJS\putting all together\toDoList\node_modules\express\lib\router\index.js:335:12)
    at next (E:\Full-Stack-Developer\EJS\putting all together\toDoList\node_modules\express\lib\router\index.js:275:10)
    at serveStatic (E:\Full-Stack-Developer\EJS\putting all together\toDoList\node_modules\serve-static\index.js:75:16)
    at Layer.handle [as handle_request] (E:\Full-Stack-Developer\EJS\putting all together\toDoList\node_modules\express\lib\router\layer.js:95:5)
    at trim_prefix (E:\Full-Stack-Developer\EJS\putting all together\toDoList\node_modules\express\lib\router\index.js:317:13)
    at E:\Full-Stack-Developer\EJS\putting all together\toDoList\node_modules\express\lib\router\index.js:284:7 
  messageFormat: undefined,
  stringValue: `" name: 'Delete' "`,
  kind: 'ObjectId',
  value:  name: 'Delete' ,
  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 (E:\Full-Stack-Developer\EJS\putting all together\toDoList\node_modules\bson\lib\bson\objectid.js:59:11)
      at castObjectId (E:\Full-Stack-Developer\EJS\putting all together\toDoList\node_modules\mongoose\lib\cast\objectid.js:25:12)
      at ObjectId.cast (E:\Full-Stack-Developer\EJS\putting all together\toDoList\node_modules\mongoose\lib\schema\objectid.js:279:12)
      at ObjectId.SchemaType.applySetters (E:\Full-Stack-Developer\EJS\putting all together\toDoList\node_modules\mongoose\lib\schematype.js:1104:12)
      at ObjectId.SchemaType._castForQuery (E:\Full-Stack-Developer\EJS\putting all together\toDoList\node_modules\mongoose\lib\schematype.js:1539:15)
      at ObjectId.SchemaType.castForQuery (E:\Full-Stack-Developer\EJS\putting all together\toDoList\node_modules\mongoose\lib\schematype.js:1529:15)
      at ObjectId.SchemaType.castForQueryWrapper (E:\Full-Stack-Developer\EJS\putting all together\toDoList\node_modules\mongoose\lib\schematype.js:1506:20)
      at cast (E:\Full-Stack-Developer\EJS\putting all together\toDoList\node_modules\mongoose\lib\cast.js:274:34)
      at model.Query.Query.cast (E:\Full-Stack-Developer\EJS\putting all together\toDoList\node_modules\mongoose\lib\query.js:4801:12)
      at castQuery (E:\Full-Stack-Developer\EJS\putting all together\toDoList\node_modules\mongoose\lib\query.js:4601:18)
      at model.Query.Query._findAndModify (E:\Full-Stack-Developer\EJS\putting all together\toDoList\node_modules\mongoose\lib\query.js:3461:23)
      at model.Query.<anonymous> (E:\Full-Stack-Developer\EJS\putting all together\toDoList\node_modules\mongoose\lib\query.js:3424:8)
      at model.Query._wrappedThunk [as _findOneAndRemove] (E:\Full-Stack-Developer\EJS\putting all together\toDoList\node_modules\mongoose\lib\helpers\query\wrapThunk.js:16:8)
      at E:\Full-Stack-Developer\EJS\putting all together\toDoList\node_modules\kareem\index.js:370:33
      at processTicksAndRejections (internal/process/task_queues.js:75:11)

  _id: 6058941ad1f874331c5bd61b, name: ''   Delete  null

events.js:292
      throw er; // Unhandled 'error' event
      ^

TypeError: Cannot read property 'push' of null
    at E:\Full-Stack-Developer\EJS\putting all together\toDoList\app.js:99:19
    at E:\Full-Stack-Developer\EJS\putting all together\toDoList\node_modules\mongoose\lib\model.js:4870:16
    at E:\Full-Stack-Developer\EJS\putting all together\toDoList\node_modules\mongoose\lib\model.js:4870:16
    at E:\Full-Stack-Developer\EJS\putting all together\toDoList\node_modules\mongoose\lib\helpers\promiseOrCallback.js:24:16
    at E:\Full-Stack-Developer\EJS\putting all together\toDoList\node_modules\mongoose\lib\model.js:4893:21
    at E:\Full-Stack-Developer\EJS\putting all together\toDoList\node_modules\mongoose\lib\query.js:4400:11
    at E:\Full-Stack-Developer\EJS\putting all together\toDoList\node_modules\kareem\index.js:136:16
    at processTicksAndRejections (internal/process/task_queues.js:75:11)
Emitted 'error' event on Function instance at:
    at E:\Full-Stack-Developer\EJS\putting all together\toDoList\node_modules\mongoose\lib\model.js:4872:13
    at E:\Full-Stack-Developer\EJS\putting all together\toDoList\node_modules\mongoose\lib\helpers\promiseOrCallback.js:24:16
    [... lines matching original stack trace ...]
    at processTicksAndRejections (internal/process/task_queues.js:75:11)

EJS 文件

 <%- include("header") -%>

  <div class="box" id="heading">
    <h1> <%= listTitle %> </h1>
  </div>

  <div class="box">
    <% newListItems.forEach(function(item) %>
      <form action="/delete" method="post">
        <div class="item">
          <input 
            type="checkbox" 
            onchange="this.form.submit()" 
            value="<%= item._id %>" 
            name="checkbox"
          >
          <p><%=  item.name  %></p>
        </div>
        <input 
          type='hidden' 
          name="listName"
          value="<%= listTitle %>" 
        >
      </form>
    <% ); %>


      <form 
        class="item" 
        action="/" 
        method="post"
      >
        <input 
          type="text" 
          name="newItem" 
          placeholder="New Item" 
          autocomplete="off"
        >
        <button 
          type="submit" 
          name="list" 
          value=" <%= listTitle %> "
        >+</button>
      </form>
  </div>

<%- include("footer") -%>

带有 app.post('delete') 的 app.js 已启动错误

c//jshint esversion:6

const express = require("express");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");
const _ = require('lodash');

const  Schema  = mongoose;

const date = require(__dirname + "/date.js");
var today = date.getDate();

const app = express();

app.set('view engine', 'ejs');

app.use(bodyParser.urlencoded(extended: true));
app.use(express.static("public"));

mongoose.connect("mongodb://localhost:27017/todolistDB", 
  useNewUrlParser: true, 
  useUnifiedTopology: true,
  useFindAndModify: true,
  useCreateIndex : true
);  //useNewUrlParser: true is used for avoiding the deprecation warning

const itemsSchema = new Schema(
  name: String 
);

const Item = mongoose.model("Item", itemsSchema);  // Collections name is Items, so we use singular form in model as 'Item'

const item1 = new Item( name: "Hey, today's do list.");
const item2 = new Item( name: "Hit the + button to add a new item");
const item3 = new Item( name: "<= Hit this checkbox to delete an item.");
const defaultItems = [item1, item2, item3];

// const items = ["Buy Food", "Cook Food", "Eat Food"];
// const workItems = [];

const listSchema = new Schema(
  name: String,
  items: [itemsSchema]
);

const List = mongoose.model('List', listSchema);


app.get("/", function(req, res) 
  Item.find(, function(err, foundItems)
    console.log(foundItems);
    if (foundItems.length === 0)
      Item.insertMany(defaultItems, function(err)
        if (err)
          console.log(err);
         else 
          console.log("Successfully saved the default items to DB.");  
         
        res.redirect("/");
      );
     else
      console.log(today);
      res.render("list", 
        
          listTitle: today, 
          newListItems: foundItems
        
      );
    
  );
);

app.post("/", function(req, res)
  const itemName = req.body.newItem;
  const item = new Item(  name: itemName  );
  const listName = req.body.list;
  // console.log(itemName, item, listName);

  if (listName === today)
    item.save(function (err) 
      if (err) 
        console.log(err);
        return handleError(err);
       else 
        console.log('successfully saved inside "/" route content under todays date');
      
    );
    res.redirect("/");
    console.log( itemName, item, listName); 
    //test add  _id: 6058562ddb96b030fcddc85e, name: 'test add'   Clintoayamkudi  
   else 
     List.findOne(name : listName , function(err, foundList)

      if (err)
        console.log(err, itemName, item, listName);
       else  
        console.log( itemName, item, listName, foundList);
        //test add  _id: 6058562ddb96b030fcddc85e, name: 'test add'   Clintoayamkudi  null
        foundList.push(item);
        // foundList.markModified('items');           // basically it helps in saving the modified files , since items is not readable -not helpful.
        foundList.save();
        res.redirect('/' + listName);
      
    );

  
  // if (req.body.list === "Work") 
  //   workItems.push(item);
  //   res.redirect("/work");
  //  else 
  //   items.push(item);
  //   res.redirect("/");
  // 

);

app.post("/delete", function(req, res)
  const checkedItemId = req.body.checkbox;
  const listName = req.body.listName;
  console.log(checkedItemId, req.body, listName);
  //605315035dbba527c004e58e  checkbox: '605315035dbba527c004e58e', listName: 'Monday, March 22'  Monday, March 22
  if(listName === today)
    Item.findByIdAndRemove(checkedItemId, function(err)
      if(!err)
        console.log("successfully removed the checked item from the item list!!!");
        res.redirect("/");
       
    );
   else 
    console.log(checkedItemId, listName);
    //605878c7707cee19145c7779 Clinto92
    List.findByIdAndRemove(
      
        name: listName
      , 
      
        $pull : 
                  _id : checkedItemId
                
      , 
    function(err)
      if(!err)
        res.redirect('/' + listName);
       else 
        console.log(err);
      
    );
  
  
);


app.get("/:customListName", function(req,res)
  const customListName = _.capitalize(req.params.customListName);

  List.findOne(name : customListName, function(err, foundList)
    if(!err)
      if (!foundList)
        console.log("data doesn't exist");
        // create new list
        const list = new List(
          name: customListName,
          items: defaultItems
        ); 
        list.save();
        res.redirect('/' + customListName);
       else 
        console.log('the searched data exist in the mongoDB');
        // show the existing list
        res.render('list', 
          listTitle: foundList.name, 
          newListItems: foundList.items
        );
      
     else 
      console.log(err);
    
  );  
);


app.get("/:customListName/about", function(req, res)
  res.render("about");
);

app.listen(3000, function() 
  console.log("Server started on port 3000");
);

超级终端错误

我将猫鼬版本降级为npm install mongoose@4.7.2 更好地理解所有参数如下所示:

MongooseError [CastError]: Cast to ObjectId failed for value " name: 'C' " at path "_id" for model "List"
    at new CastError (E:\Full-Stack-Developer\EJS\putting all together\toDoList\node_modules\mongoose\lib\error\cast.js:26:11)
    at ObjectId.cast (E:\Full-Stack-Developer\EJS\putting all together\toDoList\node_modules\mongoose\lib\schema\objectid.js:147:13)
    at ObjectId.castForQuery (E:\Full-Stack-Developer\EJS\putting all together\toDoList\node_modules\mongoose\lib\schema\objectid.js:187:15)
    at cast (E:\Full-Stack-Developer\EJS\putting all together\toDoList\node_modules\mongoose\lib\cast.js:192:34)
    at model.Query.Query.cast (E:\Full-Stack-Developer\EJS\putting all together\toDoList\node_modules\mongoose\lib\query.js:2742:12)
    at castQuery (E:\Full-Stack-Developer\EJS\putting all together\toDoList\node_modules\mongoose\lib\query.js:2648:18)
    at model.Query.Query._findAndModify (E:\Full-Stack-Developer\EJS\putting all together\toDoList\node_modules\mongoose\lib\query.js:1857:17)
    at model.Query.Query.findOneAndRemove (E:\Full-Stack-Developer\EJS\putting all together\toDoList\node_modules\mquery\lib\mquery.js:2272:15)
    at model.Query.Query._findOneAndRemove (E:\Full-Stack-Developer\EJS\putting all together\toDoList\node_modules\mongoose\lib\query.js:1832:31)
    at E:\Full-Stack-Developer\EJS\putting all together\toDoList\node_modules\kareem\index.js:239:8
    at E:\Full-Stack-Developer\EJS\putting all together\toDoList\node_modules\kareem\index.js:18:7
    at processTicksAndRejections (internal/process/task_queues.js:75:11) 
  stringValue: `" name: 'C' "`,
  kind: 'ObjectId',
  value:  name: 'C' ,
  path: '_id',
  reason: undefined,
  model: [Function: model] 
    hooks: Kareem  _pres: , _posts:  ,
    base: Mongoose 
      connections: [Array],
      plugins: [],
      models: [Object],
      modelSchemas: [Object],
      options: [Object]
    ,
    modelName: 'List',
    model: [Function: model],
    db: NativeConnection 
      base: [Mongoose],
      collections: [Object],
      models: [Object],
      config: [Object],
      replica: false,
      hosts: null,
      host: 'localhost',
      port: 27017,
      user: undefined,
      pass: undefined,
      name: 'todolistDB',
      options: [Object],
      otherDbs: [],
      _readyState: 1,
      _closeCalled: false,
      _hasOpened: true,
      _listening: false,
      db: [Db]
    ,
    discriminators: undefined,
    schema: Schema 
      obj: [Object],
      paths: [Object],
      subpaths: ,
      virtuals: [Object],
      singleNestedPaths: ,
      nested: ,
      inherits: ,
      callQueue: [Array],
      _indexes: [],
      methods: ,
      statics: ,
      tree: [Object],
      _requiredpaths: [],
      discriminatorMapping: undefined,
      _indexedpaths: undefined,
      query: ,
      childSchemas: [Array],
      s: [Object],
      options: [Object],
      '$globalPluginsApplied': true
    ,
    collection: NativeCollection 
      collection: [Collection],
      opts: [Object],
      name: 'lists',
      collectionName: 'lists',
      conn: [NativeConnection],
      queue: [],
      buffer: false,
      emitter: [EventEmitter]
    ,
    Query: [Function (anonymous)]  base: [Object] ,
    '$__insertMany': [Function (anonymous)],
    insertMany: [Function (anonymous)]
  

提前谢谢你!

【问题讨论】:

【参考方案1】:

这是导致错误的原因:

List.findByIdAndRemove(
      
        name: listName
      , 
      
        $pull : 
                  _id : checkedItemId
                
      , 

如果你想在 mongo 中使用“findById”,你必须传递一个有效的 mongodb id。我相信 listName 被解析为'C',所以你正在使用 name:'C'

进行查询

【讨论】:

以上是关于MongooseError [CastError]:模型“List”的路径“_id”的值“ name:'C'”转换为 ObjectId 失败的主要内容,如果未能解决你的问题,请参考以下文章

MongooseError - 操作缓冲在 10000 毫秒后超时

MongooseError [ParallelSaveError]:无法并行保存()同一个文档

MongooseError:操作“featureds.find()”缓冲在 10000 毫秒后超时

MongooseError:操作“featureds.find()”缓冲在 10000 毫秒后超时

MongooseError:操作 `products.insertOne()` 缓冲在 10000 毫秒后超时

MongooseError:操作 `blacklistScema.find()` 缓冲在 10000 毫秒后超时