javascript mongoose.js CastError:对于路径“未定义”处的值“[object Object]”,转换为数字失败

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15004837/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 23:06:52  来源:igfitidea点击:

mongoose.js CastError: Cast to number failed for value "[object Object]" at path "undefined"

javascriptmongooseschema

提问by Matthew Clark

Using Mongoose.jswith node.js.

使用Mongoose.jsnode.js

I have this schema:

我有这个架构:

var Photo = new Schema({
     URL:String
    ,description:String
    ,created_by:{type:ObjectId, ref:'User'}
    ,created_at:{type:Date, default:Date.now()}
});

var User = new Schema({
    name:{type:String,index:true}
    ,email:{type:String,index:true, unique:true}
});

//Task model                                                                                                                                                                                       
var Task = new Schema({
    title:String
   ,created_by:{type:ObjectId, ref: 'User'}
   ,created:{type:Date, default:Date.now()}
   ,responses:[{
       type:Number
      ,user:{type:ObjectId, ref: 'User'}
       ,comment:String
       ,avatarURL:String
       ,photo:{type:ObjectId, ref: 'Photo'}
      ,created:{type:Date, default:Date.now()}
   }]
});

//Group model                                                                                                                                                                                      
var Group = new Schema({
     name:String
    ,tasks:[Task]
});

and this code errors out (group is fine, task at that idx is fine,responses is an empty array,user is valid,photo is valid):

并且此代码出错(组很好,该 idx 处的任务很好,响应是一个空数组,用户有效,照片有效):

var typePhoto = 6;
 var resp = {
      type: typePhoto//photo                                                                                                                                                 
      ,user: user._id
      ,photo: photo._id
 };


 group.tasks[taskIdx].responses.push(resp); //errors out here

at that point I get the following error:

那时我收到以下错误:

/home/admin/notitws/node_modules/mongoose/lib/utils.js:434
        throw err;
              ^
CastError: Cast to number failed for value "[object Object]" at path "undefined"
    at SchemaNumber.cast (/home/admin/notitws/node_modules/mongoose/lib/schema/number.js:127:9)
    at Array.MongooseArray._cast (/home/admin/notitws/node_modules/mongoose/lib/types/array.js:78:15)
    at Object.map (native)
    at Array.MongooseArray.push (/home/admin/notitws/node_modules/mongoose/lib/types/array.js:187:23)
    at exports.taskAddPhoto (/home/admin/notitws/routes/group.js:1097:35)
    at Promise.exports.createPhoto (/home/admin/notitws/routes/photos.js:106:4)
    at Promise.addBack (/home/admin/notitws/node_modules/mongoose/lib/promise.js:128:8)
    at Promise.EventEmitter.emit (events.js:96:17)
    at Promise.emit (/home/admin/notitws/node_modules/mongoose/lib/promise.js:66:38)
    at Promise.complete (/home/admin/notitws/node_modules/mongoose/lib/promise.js:77:20)

Any ideas on how to fix this or what may be causing it?

有关如何解决此问题或可能导致此问题的任何想法?

PS Don't know if it matters but in the call to get group I am populating tasks.responses.userand tasks.responses.photoand tasks.created_by.

PS不知道它的问题,但在调用get我填充组tasks.responses.usertasks.responses.phototasks.created_by

回答by Jean-Philippe Leclerc

The "type" keyword is used by mongoose to determine the type of the field. Mongoose probably thinks that responses is of type Number instead of array.

mongoose 使用“type”关键字来确定字段的类型。Mongoose 可能认为响应的类型是 Number 而不是数组。

Try:

尝试:

responses:[{
   type: {type: Number}
   ,user:{type:ObjectId, ref: 'User'}
   ,comment:String
   ,avatarURL:String
   ,photo:{type:ObjectId, ref: 'Photo'}
   ,created:{type:Date, default:Date.now()}
}]

Another alternative would be to wrap your response object into a schema then:

另一种选择是将您的响应对象包装到架构中,然后:

responses: [Response]

回答by Zafer Fatih Koyuncu

I am posting what fixed my casting to objectId. It is the story of updatedBy key of my features document. I added some comments to show you the problematic area corresponds to the casting issue.

我正在发布将我的转换固定到 objectId 的内容。这是我的功能文档的 updatedBy 键的故事。我添加了一些评论以向您展示与铸造问题相对应的问题区域。

import mongoose;

进口猫鼬;

    var mongoose = require('mongoose');

define objectId;

定义对象ID;

    var ObjectId = mongoose.Schema.Types.ObjectId;

define the type in your schema;

在您的架构中定义类型;

    var featureSchema = new Schema({
        name: String,
        isSystem: { type: Number, min: 0, max: 1 },
        updatedBy: {type:ObjectId, ref:'users'}, //here I defined the field!
        updatedAt: { type: Date, default: Date.now }
});

and then insert the document via post method;

然后通过post方法插入文档;

    app.post('/features', function (req, res){
          var feature;
          console.log("POST: ");
          console.log(req.body);
          feature = new Feature({
                   name: req.body.name,
                   isSystem: req.body.isSystem,
                   updatedBy: req.body.updatedBy, //here I insert the objectId field
                   updatedAt: new Date()
          });
          feature.save(function (err) {
                   if (!err) {
                            return console.log("created");
                   } else {
                        return console.log(err);
                   }
          });
         return res.json({ features: feature });
    });

and finally this is your json string. you can fire it from google chrome javascript console or a similar one;

最后这是你的 json 字符串。您可以从 google chrome javascript 控制台或类似的控制台启动它;

    jQuery.post("/features", {
                "name": "Receipt",
                "isSystem": 0,
                "updatedBy": "528f3d44afcb60d90a000001" 
     },function (data, textStatus, jqXHR) {
                 console.log("Post resposne:"); console.dir(data);                 
                 console.log(textStatus);                             
                 console.dir(jqXHR);
     });