Ошибка MongooseError [CastError]: Приведение к объекту не удалось для значения «{ имя: ‘C’ }» по пути «_id» для модели «Список»

#mongoose #ejs #mongoose-schema

Вопрос:

Чтобы сделать приложение с помощью мангуста и ejs

Я попытался деградировать другую версию мангуста, чтобы уловить проблему. Тоже пытался утешить.регистрируйте проблемы, из которых я узнал, что коллекция списков собирает данные с помощью метода .save (), в то время как коллекция элементов не может быть сохранена. Это происходит после того, как найденный список приложения.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" amp;amp; 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"
  }
}

 

Обновлена версия npm для мангуста, ошибки в hyper :

 CastError: Cast to ObjectId failed for value "{ name: 'Delete' }" at path "_id" for model "List"
    at model.Query.exec (E:Full-Stack-DeveloperEJSputting all togethertoDoListnode_modulesmongooselibquery.js:4361:21)
    at model.Query.Query.findOneAndRemove (E:Full-Stack-DeveloperEJSputting all togethertoDoListnode_modulesmongooselibquery.js:3108:8)
    at Function.Model.findOneAndRemove (E:Full-Stack-DeveloperEJSputting all togethertoDoListnode_modulesmongooselibmodel.js:2909:13)
    at Function.Model.findByIdAndRemove (E:Full-Stack-DeveloperEJSputting all togethertoDoListnode_modulesmongooselibmodel.js:2961:15)
    at E:Full-Stack-DeveloperEJSputting all togethertoDoListapp.js:132:10
    at Layer.handle [as handle_request] (E:Full-Stack-DeveloperEJSputting all togethertoDoListnode_modulesexpresslibrouterlayer.js:95:5)
    at next (E:Full-Stack-DeveloperEJSputting all togethertoDoListnode_modulesexpresslibrouterroute.js:137:13)
    at Route.dispatch (E:Full-Stack-DeveloperEJSputting all togethertoDoListnode_modulesexpresslibrouterroute.js:112:3)
    at Layer.handle [as handle_request] (E:Full-Stack-DeveloperEJSputting all togethertoDoListnode_modulesexpresslibrouterlayer.js:95:5)
    at E:Full-Stack-DeveloperEJSputting all togethertoDoListnode_modulesexpresslibrouterindex.js:281:22
    at Function.process_params (E:Full-Stack-DeveloperEJSputting all togethertoDoListnode_modulesexpresslibrouterindex.js:335:12)
    at next (E:Full-Stack-DeveloperEJSputting all togethertoDoListnode_modulesexpresslibrouterindex.js:275:10)
    at serveStatic (E:Full-Stack-DeveloperEJSputting all togethertoDoListnode_modulesserve-staticindex.js:75:16)
    at Layer.handle [as handle_request] (E:Full-Stack-DeveloperEJSputting all togethertoDoListnode_modulesexpresslibrouterlayer.js:95:5)
    at trim_prefix (E:Full-Stack-DeveloperEJSputting all togethertoDoListnode_modulesexpresslibrouterindex.js:317:13)
    at E:Full-Stack-DeveloperEJSputting all togethertoDoListnode_modulesexpresslibrouterindex.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-DeveloperEJSputting all togethertoDoListnode_modulesbsonlibbsonobjectid.js:59:11)
      at castObjectId (E:Full-Stack-DeveloperEJSputting all togethertoDoListnode_modulesmongooselibcastobjectid.js:25:12)
      at ObjectId.cast (E:Full-Stack-DeveloperEJSputting all togethertoDoListnode_modulesmongooselibschemaobjectid.js:279:12)
      at ObjectId.SchemaType.applySetters (E:Full-Stack-DeveloperEJSputting all togethertoDoListnode_modulesmongooselibschematype.js:1104:12)
      at ObjectId.SchemaType._castForQuery (E:Full-Stack-DeveloperEJSputting all togethertoDoListnode_modulesmongooselibschematype.js:1539:15)
      at ObjectId.SchemaType.castForQuery (E:Full-Stack-DeveloperEJSputting all togethertoDoListnode_modulesmongooselibschematype.js:1529:15)
      at ObjectId.SchemaType.castForQueryWrapper (E:Full-Stack-DeveloperEJSputting all togethertoDoListnode_modulesmongooselibschematype.js:1506:20)
      at cast (E:Full-Stack-DeveloperEJSputting all togethertoDoListnode_modulesmongooselibcast.js:274:34)
      at model.Query.Query.cast (E:Full-Stack-DeveloperEJSputting all togethertoDoListnode_modulesmongooselibquery.js:4801:12)
      at castQuery (E:Full-Stack-DeveloperEJSputting all togethertoDoListnode_modulesmongooselibquery.js:4601:18)
      at model.Query.Query._findAndModify (E:Full-Stack-DeveloperEJSputting all togethertoDoListnode_modulesmongooselibquery.js:3461:23)
      at model.Query.<anonymous> (E:Full-Stack-DeveloperEJSputting all togethertoDoListnode_modulesmongooselibquery.js:3424:8)
      at model.Query._wrappedThunk [as _findOneAndRemove] (E:Full-Stack-DeveloperEJSputting all togethertoDoListnode_modulesmongooselibhelpersquerywrapThunk.js:16:8)
      at E:Full-Stack-DeveloperEJSputting all togethertoDoListnode_moduleskareemindex.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-DeveloperEJSputting all togethertoDoListapp.js:99:19
    at E:Full-Stack-DeveloperEJSputting all togethertoDoListnode_modulesmongooselibmodel.js:4870:16
    at E:Full-Stack-DeveloperEJSputting all togethertoDoListnode_modulesmongooselibmodel.js:4870:16
    at E:Full-Stack-DeveloperEJSputting all togethertoDoListnode_modulesmongooselibhelperspromiseOrCallback.js:24:16
    at E:Full-Stack-DeveloperEJSputting all togethertoDoListnode_modulesmongooselibmodel.js:4893:21
    at E:Full-Stack-DeveloperEJSputting all togethertoDoListnode_modulesmongooselibquery.js:4400:11
    at E:Full-Stack-DeveloperEJSputting all togethertoDoListnode_moduleskareemindex.js:136:16
    at processTicksAndRejections (internal/process/task_queues.js:75:11)
Emitted 'error' event on Function instance at:
    at E:Full-Stack-DeveloperEJSputting all togethertoDoListnode_modulesmongooselibmodel.js:4872:13
    at E:Full-Stack-DeveloperEJSputting all togethertoDoListnode_modulesmongooselibhelperspromiseOrCallback.js:24:16
    [... lines matching original stack trace ...]
    at processTicksAndRejections (internal/process/task_queues.js:75:11)
 

EJS FILE

  <%- 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.js with app.post(‘delete’) has errors initiated

 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-DeveloperEJSputting all togethertoDoListnode_modulesmongooseliberrorcast.js:26:11)
    at ObjectId.cast (E:Full-Stack-DeveloperEJSputting all togethertoDoListnode_modulesmongooselibschemaobjectid.js:147:13)
    at ObjectId.castForQuery (E:Full-Stack-DeveloperEJSputting all togethertoDoListnode_modulesmongooselibschemaobjectid.js:187:15)
    at cast (E:Full-Stack-DeveloperEJSputting all togethertoDoListnode_modulesmongooselibcast.js:192:34)
    at model.Query.Query.cast (E:Full-Stack-DeveloperEJSputting all togethertoDoListnode_modulesmongooselibquery.js:2742:12)
    at castQuery (E:Full-Stack-DeveloperEJSputting all togethertoDoListnode_modulesmongooselibquery.js:2648:18)
    at model.Query.Query._findAndModify (E:Full-Stack-DeveloperEJSputting all togethertoDoListnode_modulesmongooselibquery.js:1857:17)
    at model.Query.Query.findOneAndRemove (E:Full-Stack-DeveloperEJSputting all togethertoDoListnode_modulesmquerylibmquery.js:2272:15)
    at model.Query.Query._findOneAndRemove (E:Full-Stack-DeveloperEJSputting all togethertoDoListnode_modulesmongooselibquery.js:1832:31)
    at E:Full-Stack-DeveloperEJSputting all togethertoDoListnode_moduleskareemindex.js:239:8
    at E:Full-Stack-DeveloperEJSputting all togethertoDoListnode_moduleskareemindex.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
                }
      }, 
 

если вы хотите использовать «findById» с mongo, вам необходимо передать действительный идентификатор mongodb. Я верю, что имя списка разрешено как «C», поэтому вы запрашиваете {имя: «C»}