mongoose模式检查是否第一次保存模型实例

时间:2014-01-25 10:33:46

标签: node.js mongodb mongoose

我有3个模式,其中2个有.pre('save')钩子将其_id推入前一个模式。您可以以论坛为例,其中包含主题,问题和评论

var topicSchema = new Schema({
  arr: {type:[Schema.ObjectId], ref:'Question'},
});
var Topic = new mongoose.model('Topic', topicSchema);

var questionSchema = new Schema({
  targetId: {type:Schema.ObjectId, ref:'Topic', required:true},
  arr: {type:[Schema.ObjectId], ref:'Comment'},
});
var Question = new mongoose.model('Question', questionSchema);

var commentSchema = new Schema({
  targetId: {type:Schema.ObjectId, ref:'Question', required:true},
});
var Comment = new mongoose.model('Comment', commentSchema);

现在我想要上面的架构:当我保存一个问题时,我想自动将问题的_id推送到各自的Topic.arr,当我保存评论时自动将其推送到各自的Question.arr .pre('save')

我尝试使用function addPreSave (schema, idProperty, containerProperty) { var modelName = schema.paths[idProperty].options.ref; var model = mongoose.models[modelName]; schema.pre('save', function (next) { model.findById(this[idProperty], function (err, doc) { doc[containerProperty].push(this._id); doc.save(next); }.bind(this)); }); } addPreSave(questionSchema, 'targetId', 'arr'); addPreSave(commentSchema, 'targetId', 'arr'); 挂钩解决此问题,如下所示:

.pre('save')

上述函数所做的所有操作(以及对它的2次调用)都是为2个模式中的每一个添加_id挂钩,以便在其各自的父模式中添加Topic.arr


问题:问题在于,现在,每次我保存评论时,它都会将其ID推送到主题,但我实际上只是想第一次这样做。因此,在上面的示例中,如果您创建主题,然后是问题,然后是问题的评论,则_id将包含2个ID(问题的{{1}}的两倍),因为它会保存一次问题和第二次由评论保存问题的电话触发

有没有人知道解决这个问题的方法,或者更具体地说,如果您知道如何在预保存挂钩中弄清楚这是否是第一次保存?

1 个答案:

答案 0 :(得分:11)

因此,如果您愿意继续使用Google的第二页,您可以找到答案!

为每个名为 isNew 的文档定义了一个属性,它可以实现您的想象。因此,只需在方法中添加if (!this.isNew) return next()即可解决问题。