我正在尝试在 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 .
我该如何解决这个问题?
最佳答案
您引用的 mongoose 文档中的示例将 Number
用于 personSchema._id
字段,将 ObjectId
用于其他字段。
我认为他们在示例中这样做只是为了证明两者都可以使用。如果您未在架构中指定 _id
,则 ObjectId
将是默认值。
在这里,您的所有记录都有一个 _id
字段,它是一个 ObjectId
,但您将它们视为数字。此外,personID
和 taskID
等字段不存在,除非您省略了定义它们的部分。
如果您确实想为所有 _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
Hook 中。
关于javascript - Mongoose:转换为 ObjectId 的值失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15771470/