【问题标题】:Mongoose: Cast to ObjectId failed for valueMongoose:转换为 ObjectId 的值失败
【发布时间】:2013-03-24 04:21:45
【问题描述】:

我正在尝试在 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:"tony@starkindustries.com" });
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);
})

我创建了架构并尝试保存一些数据。

错误:

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

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

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

我该如何解决这个问题?

【问题讨论】:

    标签: javascript node.js mongodb mongoose populate


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      您引用的 mongoose 文档中的示例将 Number 用于 personSchema._id 字段,将 ObjectId 用于其他字段。

      我认为他们在示例中这样做只是为了证明两者都可以使用。如果您未在架构中指定_id,则ObjectId 将是默认值。

      在这里,您的所有记录都有一个_id 字段,即ObjectId,但您将它们视为数字。此外,personIDtaskID 之类的字段不存在,除非您省略了定义它们的部分。

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

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

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

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

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

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

      【讨论】:

      • 感谢帮助,但在查询和填充时,我得到一个错误。你碰巧知道我做错了什么吗? (更新了问题)
      • 你保存了吗?似乎它应该可以工作,除非它正在加载以前没有创建者保存的新闻项目。
      • 我将保存部分添加到问题及其触发的错误中
      • 就像我在回答中所说的那样,creator 引用的类型必须是 Number,而不是 ObjectId。是的,您上面的代码不正确。 findOne 查询需要在回调中才能检索这些新记录。而且,如果您没有在运行此脚本之间转储数据库,那么您只是在重复加载第一个匹配“NY”的数据库。
      • 所以我应该先保存任务和人员,然后再保存 newsitem ?
      猜你喜欢
      • 2021-09-05
      • 2021-03-09
      • 1970-01-01
      • 2018-01-06
      • 1970-01-01
      • 2021-03-14
      • 2020-04-18
      • 2020-12-16
      • 2022-08-15
      相关资源
      最近更新 更多