【问题标题】:is there a way to define a Model in mongoose that does not have the .save() method?有没有办法在没有 .save() 方法的猫鼬中定义模型?
【发布时间】:2012-07-31 01:03:04
【问题描述】:

我要做的是定义一个 Student 模型,其中包含一个名为“schedules”的字段,其中包含一个 Schedule 实例数组,但我不希望 Schedule 模型能够保存到它自己的集合中。

这是一些代码,它会更有意义:

var ScheduleSchema = new Schema({
    day:    {type: Number, min: 0, max: 6},
    time:   {type: Number, min: 0, max:24}
});

var StudentSchema = new Schema({
    firstName:  String,
    schedule:   [ScheduleSchema]
});

var Schedule = mongoose.model("Schedule", ScheduleSchema);
var Student = mongoose.model(modelName, StudentSchema);
Student.Schedule = Schedule;

我在这段代码中遇到的问题是,当我这样做时:

var schedule = new Student.Schedule({day: 3, time: 15});

当我使用 console.log 时,我会得到类似的东西

{ "day" : 3, "time" : 15, "_id" : ObjectId("5019f34924ee03e20900001a") }

通过在模式中明确定义 _id,我绕过了 _id 的自动生成,

var ScheduleSchema = new Schema({
    _id:    ObjectIdSchema,
    day:    {type: Number, min: 0, max: 6},
    time:   {type: Number, min: 0, max:24}
});

现在它只是给了我:

{ "day" : 3, "time" : 15}

这可能是一个 hack.. 而不是我想要依赖的东西。

另一个问题是,如果我这样做了

schedule.save()

它实际上会创建一个集合并将文档保存到数据库中。

有没有办法为 Schedule 禁用 save()?有正确的方法吗?

我可能会坚持我所拥有的,或者满足于混合类型但在验证上失败..

【问题讨论】:

    标签: validation node.js model mongoose


    【解决方案1】:

    你为什么还要schedule.save()?您应该保存父对象(即Student 对象),而不是嵌入文档。如果您保存schedule,则默认情况下会附加_id。如果您将带有schedule 的Student 对象保存为嵌入文档,则不会发生这种情况。

    此外,没有真正的理由在您的 Schedule 模型上禁用 .save 方法(这是一个有趣的功能,它允许您将 Schedule 模型作为嵌入式文档的模型和独立文档的模型同时)。只是不要使用它。做这样的事情:

    var student = new Student({ firstName: 'John' });
    var schedule = new Schedule({ day: 3, time: 15 });
    student.schedules.push( schedule );
    student.save( );
    

    【讨论】:

    • 当然我不会做 schedule.save() 因为我写了这个。我只是不希望模棱两可的代码能够做它不应该做的事情。您还提到如果我确实保存了学生,则不会生成“_id”,但我能获得这种行为的唯一方法是添加我在 ScheduleSchema 中所做的“_id”黑客。除非那不是黑客,我只是在他们的文档中找不到任何记录。
    • 真的吗?我目前无法对其进行测试,但我会在几个小时内回复您。
    • 是的,我用 mocha 编写了测试。我只有通过将 _id: ObjectIdSchema 添加到 ScheduleSchema 来通过测试。我正在使用猫鼬 2.7.0 顺便说一句。
    猜你喜欢
    • 2018-04-12
    • 1970-01-01
    • 1970-01-01
    • 2012-07-21
    • 2013-05-19
    • 2013-07-04
    • 1970-01-01
    • 2020-01-12
    • 2019-08-17
    相关资源
    最近更新 更多