node.js Mongoose:转换为 ObjectId 的值失败

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15771470/
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-09-02 14:04:25  来源:igfitidea点击:

Mongoose: Cast to ObjectId failed for value

javascriptnode.jsmongodbmongoosepopulate

提问by Olivier_s_j

I'm trying to specify the schema of my db in mongoose. At the moment I do this:

我正在尝试在 mongoose 中指定我的数据库的架构。目前我这样做:

var Schema = mongoose.Schema;  
var today = new Date(2011, 11, 12, 0, 0, 0, 0);


var personSchema = new Schema({  
   _id : Number,
   name: { type: String, required: true },  
   tel: { type: String, required: true },  
   email: { type: String, required: true },
   newsitems: [{ type: Schema.Types.ObjectId, ref:'NewsItem'}]
});

var taskSchema = new Schema({ 
    _id: Number,
    description: { type: String, required: true },  
    startDate: { type: Date, required: true },
    newsitems: [{ type: Schema.Types.ObjectId, ref:'NewsItem'}]
});

var newsSchema = new Schema({
    _id: Number,
    creator : { type: Schema.Types.ObjectId, ref: 'Person' },
    task : { type: Schema.Types.ObjectId, ref: 'Task' },
    date: { type: Date, required:true },
    loc: {type: String, required: true }  
});

var NewsItem  = mongoose.model('NewsItem', newsSchema);
var Person = mongoose.model('Person', personSchema);
var Task = mongoose.model('Task', taskSchema);



var tony = new Person({_id:0, name: "Tony Stark", tel:"234234234", email:"[email protected]" });
var firstTask = new Task({_id:0, description:"Get an interview with the president", startDate:today});
var newsItem1 = new NewsItem({_id:0, creator: tony.id, task: firstTask.id, date: today, loc: "NY"});

newsItem1.save(function (err) {
  if (err) console.log(err);

    firstTask.save(function (err) {
        if (err) console.log(err);
    });

    tony.save(function (err) {
         if (err) console.log(err);
    }); 
});



NewsItem
.findOne({ loc: "NY" })
.populate('creator')
.populate('task')
.exec(function (err, newsitem) {
  if (err) console.log(err)
    console.log('The creator is %s', newsitem.creator.name);
})

I create the schemas and try to save some data.

我创建了模式并尝试保存一些数据。

The error:

错误:

{ message: 'Cast to ObjectId failed for value "0" at path "creator"',
  name: 'CastError',
  type: 'ObjectId',
  value: '0',
  path: 'creator' }

I wrote this code based on : http://mongoosejs.com/docs/populate.html#gsc.tab=0

我根据以下代码编写了此代码:http: //mongoosejs.com/docs/populate.html#gsc.tab=0

The db I try to create looks like this: Specify schema in mongoose.

我尝试创建的数据库如下所示:Specify schema in mongoose

How can I fix this?

我怎样才能解决这个问题?

回答by numbers1311407

The example from the mongoose docs you referenced uses Numberfor the personSchema._idfield, and ObjectIdfor the others.

您引用的猫鼬文档中的示例Number用于该personSchema._id领域和ObjectId其他领域。

I presume they do this in the example only to demonstrate that it's possible to use either. If you do not specify _idin the schema, ObjectIdwill be the default.

我认为他们在示例中这样做只是为了证明可以使用两者之一。如果你没有_id在schema中指定,ObjectId将会是默认的。

Here, all your records have an _idfield which is an ObjectId, yet you're treating them like numbers. Furthermore, fields like personIDand taskIDdo not exist, unless you've left out the part where you define them.

在这里,您的所有记录都有一个_id字段,它是ObjectId,但您将它们视为数字。此外,字段 likepersonIDtaskID不存在,除非您遗漏了定义它们的部分。

If you did want to use numbers for all your _idfields, you'd have to define that in the schemas.

如果您确实想为所有_id字段使用数字,则必须在架构中定义它。

var newsSchema = new Schema({
  _id: Number,
  _creator: {type: ObjectId, ref: "Person"},
  // ...
})

var personSchema = new Schema({
  _id: Number,
  // ...
})

Then to create a news item with a particular ID, and assign it to a creator:

然后创建具有特定 ID 的新闻项目,并将其分配给创建者:

var tony = new Person({_id: 0});
var newsItem = new NewsItem({_id: 0, creator: tony.id});

However the thing to note here is that when you use something other than ObjectIdas the _idfield, you're taking on the responsibility of managing these values yourself. ObjectIds are autogenerated and require no extra management.

然而,这里要注意的是,当您使用其他东西而不是ObjectId作为_id字段时,您将承担自己管理这些值的责任。ObjectIds 是自动生成的,不需要额外的管理。

Edit: I also noticed that you're storing refs on both sides of your associations. This is totally valid and you may want to do it sometimes, but note that you'd have to take care of storing the references yourself in the prehook.

编辑:我还注意到您在关联的双方都存储了 refs。这是完全有效的,有时您可能想这样做,但请注意,您必须自己将引用存储在pre钩子中。

回答by Enkode

I was receiving this error after creating a schema: CastError: Cast to ObjectId failed for value “[object Object]” at path “_id”Then modifying it and couldn't track it down. I deleted all the documents in the collection and I could add 1 object but not a second. I ended up deleting the collection in Mongo and that worked as Mongoose recreated the collection.

创建模式后我收到此错误: CastError: Cast to ObjectId failed for value “[object Object]” at path “_id”然后修改它并且无法跟踪它。我删除了集合中的所有文档,我可以添加 1 个对象,但不能添加一秒钟。我最终删除了 Mongo 中的集合,并且在 Mongoose 重新创建了该集合时起作用了。