我如何使用ID更新mongoDB数据?

问题描述 投票:0回答:1

我在客户端使用猫鼬,节点js,express和PUG。这是我的更新帖子。得到一个很好。

router.post('/entries/user/:id', (req, res) => {
  let entryUpdated={};
  console.log(req.body.chinese_name)
  
  let query = {_id:req.params.id}
  console.log(query)
  
  database.update(query,req.body.chinese_name,function(err){
    if(err){
      console.log(err);
      return;
    }else{
      res.redirect('entries')
    }
  })
    .then(() => { res.render('edit.pug', {msg: "Updated Succesfully"}); 
    })
    .catch((err) => {
      console.log(err);
      res.render('edit.pug', {msg: "Something went wrong! Make sure no field is empty."})
}) 
})

这里是哈巴狗文件:

extends layout

block style
    style
        include ../static/style1.css
    block title
        title Dev Page | altrNATIVE

block content
    .gradiantDiv
        -var message = msg || '';
        
        .messages
            .succMsg
                h2=message

        .formDiv
            form(action=`/entries/user/${entry._id}` , method="POST", class="myEntries")

                .country
                    .chineseLabel
                        label(for="Chinese Name") Chinese Product Name:
                        input(type="text" id="productName" name="chinese_name" value=entry.chinese.name)
                        
                        label(for="Chinese Company" ) Product Company Name:
                        input(type="text" id="productCompany" name="chinese_company"  value=entry.chinese.company)

                    .otherLabel
                        label(for="Other Name") Alternative Product Name:
                        input(type="text" id="productName" name="other_name" value=entry.other.name)
                        
                        label(for="Other Company" ) Company Name:
                        input(type="text" id="productCompany" name="other_company" value=entry.other.company)

                        label(for="Other Country" ) Company Country(Optional):
                        //select#country(name='other_country' value=entry.other.country)
     
                        label(for="Other Made In") Made in:
                        textarea( name="other_madeIn" id="textInput")=value=entry.other.madeIn
                           
                    .commonProductType
                        label(for="Product Category") Product Category:
                        input(type="text" id="productCategory" name="productCategory_mainCategory" value=entry.productCategory.mainCategory)
                        label(for="Product Category") Sub Category (Optional):
                        input(type="text" id="subCategory" name="productCategory_subCategory" value=entry.productCategory.subCategory)
                        
               
                       

                button.btn Submit

这是我的模式:

const mongoose = require('mongoose');


var DataSchema = new mongoose.Schema({

  chinese: {
    name: {
      type: String, 
      
      },
    
    company: {
      type: String,
      
    },  
    
  },
  other: {
    name: {
      type: String, 
      
      },
    
    company: {
      type: String,
      
    },
    madeIn:{
      type:String,
      
    },
    country:{
      type:String,
      
    },
    
  }
  ,
  productCategory: {
    mainCategory:{
      type: String,
      
    },
    subCategory:{
      type:String,
      
    }
  },
  date: {
    type: Date,
    default: Date.now
  },
  rating:{
    
  }
 

})


module.exports = mongoose.model('databaseEntries', DataSchema);

我已经尝试运行上面的代码,但是它给我错误:

TypeError: C:\Users\kenwa\Desktop\WEB\Main Folder\altrnative-Products\views\edit.pug:18
    16|
    17|         .formDiv
  > 18|             form(action=`/entries/user/${entry._id}` , method="POST", class="myEntries")
    19|
    20|                 .country
    21|                     .chineseLabel

Cannot read property '_id' of undefined
    at eval (eval at wrap (C:\Users\kenwa\Desktop\WEB\Main Folder\altrnative-Products\node_modules\pug-runtime\wrap.js:6:10), <anonymous>:165:104)
    at template (eval at wrap (C:\Users\kenwa\Desktop\WEB\Main Folder\altrnative-Products\node_modules\pug-runtime\wrap.js:6:10), <anonymous>:1239:72)
    at Object.exports.renderFile (C:\Users\kenwa\Desktop\WEB\Main Folder\altrnative-Products\node_modules\pug\lib\index.js:427:38)
    at Object.exports.renderFile (C:\Users\kenwa\Desktop\WEB\Main Folder\altrnative-Products\node_modules\pug\lib\index.js:417:21)
    at View.exports.__express [as engine] (C:\Users\kenwa\Desktop\WEB\Main Folder\altrnative-Products\node_modules\pug\lib\index.js:464:11)
    at View.render (C:\Users\kenwa\Desktop\WEB\Main Folder\altrnative-Products\node_modules\express\lib\view.js:135:8)
    at tryRender (C:\Users\kenwa\Desktop\WEB\Main Folder\altrnative-Products\node_modules\express\lib\application.js:640:10)
    at Function.render (C:\Users\kenwa\Desktop\WEB\Main Folder\altrnative-Products\node_modules\express\lib\application.js:592:3)
    at ServerResponse.render (C:\Users\kenwa\Desktop\WEB\Main Folder\altrnative-Products\node_modules\express\lib\response.js:1012:7)
    at C:\Users\kenwa\Desktop\WEB\Main Folder\altrnative-Products\routes\index.js:71:23
    at processTicksAndRejections (internal/process/task_queues.js:97:5)
This is the ID:
entries
MongooseError [CastError]: Cast to ObjectId failed for value "entries" at path "_id" for model "databaseEntries"
    at new CastError (C:\Users\kenwa\Desktop\WEB\Main Folder\altrnative-Products\node_modules\mongoose\lib\error\cast.js:29:11)
    at model.Query.exec (C:\Users\kenwa\Desktop\WEB\Main Folder\altrnative-Products\node_modules\mongoose\lib\query.js:4341:21)
    at model.Query.Query.findOne (C:\Users\kenwa\Desktop\WEB\Main Folder\altrnative-Products\node_modules\mongoose\lib\query.js:2216:8)
    at Function.findOne (C:\Users\kenwa\Desktop\WEB\Main Folder\altrnative-Products\node_modules\mongoose\lib\model.js:2219:13)
    at Function.findById (C:\Users\kenwa\Desktop\WEB\Main Folder\altrnative-Products\node_modules\mongoose\lib\model.js:2145:15)
    at C:\Users\kenwa\Desktop\WEB\Main Folder\altrnative-Products\routes\index.js:44:10
    at Layer.handle [as handle_request] (C:\Users\kenwa\Desktop\WEB\Main Folder\altrnative-Products\node_modules\express\lib\router\layer.js:95:5)
    at next (C:\Users\kenwa\Desktop\WEB\Main Folder\altrnative-Products\node_modules\express\lib\router\route.js:137:13)
    at Route.dispatch (C:\Users\kenwa\Desktop\WEB\Main Folder\altrnative-Products\node_modules\express\lib\router\route.js:112:3)
    at Layer.handle [as handle_request] (C:\Users\kenwa\Desktop\WEB\Main Folder\altrnative-Products\node_modules\express\lib\router\layer.js:95:5)
    at C:\Users\kenwa\Desktop\WEB\Main Folder\altrnative-Products\node_modules\express\lib\router\index.js:281:22
    at param (C:\Users\kenwa\Desktop\WEB\Main Folder\altrnative-Products\node_modules\express\lib\router\index.js:354:14)
    at param (C:\Users\kenwa\Desktop\WEB\Main Folder\altrnative-Products\node_modules\express\lib\router\index.js:365:14)
    at Function.process_params (C:\Users\kenwa\Desktop\WEB\Main Folder\altrnative-Products\node_modules\express\lib\router\index.js:410:3)
    at next (C:\Users\kenwa\Desktop\WEB\Main Folder\altrnative-Products\node_modules\express\lib\router\index.js:275:10)
    at Function.handle (C:\Users\kenwa\Desktop\WEB\Main Folder\altrnative-Products\node_modules\express\lib\router\index.js:174:3) {
  message: 'Cast to ObjectId failed for value "entries" at path "_id" for model "databaseEntries"',
  name: 'CastError',
  messageFormat: undefined,
  stringValue: '"entries"',
  kind: 'ObjectId',
  value: 'entries',
  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\kenwa\Desktop\WEB\Main Folder\altrnative-Products\node_modules\bson\lib\bson\objectid.js:59:11)
      at castObjectId (C:\Users\kenwa\Desktop\WEB\Main Folder\altrnative-Products\node_modules\mongoose\lib\cast\objectid.js:25:12)
      at ObjectId.cast (C:\Users\kenwa\Desktop\WEB\Main Folder\altrnative-Products\node_modules\mongoose\lib\schema\objectid.js:267:12)
      at ObjectId.SchemaType.applySetters (C:\Users\kenwa\Desktop\WEB\Main Folder\altrnative-Products\node_modules\mongoose\lib\schematype.js:1031:12)
      at ObjectId.SchemaType._castForQuery (C:\Users\kenwa\Desktop\WEB\Main Folder\altrnative-Products\node_modules\mongoose\lib\schematype.js:1459:15)
      at ObjectId.SchemaType.castForQuery (C:\Users\kenwa\Desktop\WEB\Main Folder\altrnative-Products\node_modules\mongoose\lib\schematype.js:1449:15)
      at ObjectId.SchemaType.castForQueryWrapper (C:\Users\kenwa\Desktop\WEB\Main Folder\altrnative-Products\node_modules\mongoose\lib\schematype.js:1428:15)
      at cast (C:\Users\kenwa\Desktop\WEB\Main Folder\altrnative-Products\node_modules\mongoose\lib\cast.js:317:32)
      at model.Query.Query.cast (C:\Users\kenwa\Desktop\WEB\Main Folder\altrnative-Products\node_modules\mongoose\lib\query.js:4730:12)
      at model.Query.Query._castConditions (C:\Users\kenwa\Desktop\WEB\Main Folder\altrnative-Products\node_modules\mongoose\lib\query.js:1861:10)
      at model.Query.<anonymous> (C:\Users\kenwa\Desktop\WEB\Main Folder\altrnative-Products\node_modules\mongoose\lib\query.js:2118:8)
      at model.Query._wrappedThunk [as _findOne] (C:\Users\kenwa\Desktop\WEB\Main Folder\altrnative-Products\node_modules\mongoose\lib\helpers\query\wrapThunk.js:16:8)
      at C:\Users\kenwa\Desktop\WEB\Main Folder\altrnative-Products\node_modules\kareem\index.js:369:33
      at processTicksAndRejections (internal/process/task_queues.js:79:11)
}
This is the ID:
entries
MongooseError [CastError]: Cast to ObjectId failed for value "entries" at path "_id" for model "databaseEntries"
    at new CastError (C:\Users\kenwa\Desktop\WEB\Main Folder\altrnative-Products\node_modules\mongoose\lib\error\cast.js:29:11)
    at model.Query.exec (C:\Users\kenwa\Desktop\WEB\Main Folder\altrnative-Products\node_modules\mongoose\lib\query.js:4341:21)
    at model.Query.Query.findOne (C:\Users\kenwa\Desktop\WEB\Main Folder\altrnative-Products\node_modules\mongoose\lib\query.js:2216:8)
    at Function.findOne (C:\Users\kenwa\Desktop\WEB\Main Folder\altrnative-Products\node_modules\mongoose\lib\model.js:2219:13)
    at Function.findById (C:\Users\kenwa\Desktop\WEB\Main Folder\altrnative-Products\node_modules\mongoose\lib\model.js:2145:15)
    at C:\Users\kenwa\Desktop\WEB\Main Folder\altrnative-Products\routes\index.js:44:10
    at Layer.handle [as handle_request] (C:\Users\kenwa\Desktop\WEB\Main Folder\altrnative-Products\node_modules\express\lib\router\layer.js:95:5)
    at next (C:\Users\kenwa\Desktop\WEB\Main Folder\altrnative-Products\node_modules\express\lib\router\route.js:137:13)
    at Route.dispatch (C:\Users\kenwa\Desktop\WEB\Main Folder\altrnative-Products\node_modules\express\lib\router\route.js:112:3)
    at Layer.handle [as handle_request] (C:\Users\kenwa\Desktop\WEB\Main Folder\altrnative-Products\node_modules\express\lib\router\layer.js:95:5)
    at C:\Users\kenwa\Desktop\WEB\Main Folder\altrnative-Products\node_modules\express\lib\router\index.js:281:22
    at param (C:\Users\kenwa\Desktop\WEB\Main Folder\altrnative-Products\node_modules\express\lib\router\index.js:354:14)
    at param (C:\Users\kenwa\Desktop\WEB\Main Folder\altrnative-Products\node_modules\express\lib\router\index.js:365:14)
    at Function.process_params (C:\Users\kenwa\Desktop\WEB\Main Folder\altrnative-Products\node_modules\express\lib\router\index.js:410:3)
    at next (C:\Users\kenwa\Desktop\WEB\Main Folder\altrnative-Products\node_modules\express\lib\router\index.js:275:10)
    at Function.handle (C:\Users\kenwa\Desktop\WEB\Main Folder\altrnative-Products\node_modules\express\lib\router\index.js:174:3) {
  message: 'Cast to ObjectId failed for value "entries" at path "_id" for model "databaseEntries"',
  name: 'CastError',
  messageFormat: undefined,
  stringValue: '"entries"',
  kind: 'ObjectId',
  value: 'entries',
  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\kenwa\Desktop\WEB\Main Folder\altrnative-Products\node_modules\bson\lib\bson\objectid.js:59:11)
      at castObjectId (C:\Users\kenwa\Desktop\WEB\Main Folder\altrnative-Products\node_modules\mongoose\lib\cast\objectid.js:25:12)
      at ObjectId.cast (C:\Users\kenwa\Desktop\WEB\Main Folder\altrnative-Products\node_modules\mongoose\lib\schema\objectid.js:267:12)
      at ObjectId.SchemaType.applySetters (C:\Users\kenwa\Desktop\WEB\Main Folder\altrnative-Products\node_modules\mongoose\lib\schematype.js:1031:12)
      at ObjectId.SchemaType._castForQuery (C:\Users\kenwa\Desktop\WEB\Main Folder\altrnative-Products\node_modules\mongoose\lib\schematype.js:1459:15)
      at ObjectId.SchemaType.castForQuery (C:\Users\kenwa\Desktop\WEB\Main Folder\altrnative-Products\node_modules\mongoose\lib\schematype.js:1449:15)
      at ObjectId.SchemaType.castForQueryWrapper (C:\Users\kenwa\Desktop\WEB\Main Folder\altrnative-Products\node_modules\mongoose\lib\schematype.js:1428:15)
      at cast (C:\Users\kenwa\Desktop\WEB\Main Folder\altrnative-Products\node_modules\mongoose\lib\cast.js:317:32)
      at model.Query.Query.cast (C:\Users\kenwa\Desktop\WEB\Main Folder\altrnative-Products\node_modules\mongoose\lib\query.js:4730:12)
      at model.Query.Query._castConditions (C:\Users\kenwa\Desktop\WEB\Main Folder\altrnative-Products\node_modules\mongoose\lib\query.js:1861:10)
      at model.Query.<anonymous> (C:\Users\kenwa\Desktop\WEB\Main Folder\altrnative-Products\node_modules\mongoose\lib\query.js:2118:8)
      at model.Query._wrappedThunk [as _findOne] (C:\Users\kenwa\Desktop\WEB\Main Folder\altrnative-Products\node_modules\mongoose\lib\helpers\query\wrapThunk.js:16:8)
      at C:\Users\kenwa\Desktop\WEB\Main Folder\altrnative-Products\node_modules\kareem\index.js:369:33
      at processTicksAndRejections (internal/process/task_queues.js:79:11)
}

req.body.chinese_name的console.log和查询的console.log正常。

[我想要它做什么:我希望post方法更新接收到的id的相应数据。

node.js mongodb express mongoose pug
1个回答
0
投票

有时,错误消息可能会有点不清楚或根本没有帮助。我认为应该在updatemethod的第二个参数处出现错误(我假设您要更新中文:{name}

database.update(query, {chinese.name: req.body.chinese_name},function(err){

而且,由于这是一个后期调用,我建议将正文中的所有内容都发送给您的API,而不是作为参数。它更加安全,尤其是在使用https时。

© www.soinside.com 2019 - 2024. All rights reserved.