【问题标题】:Can I perform mongoose update from post save middleware?我可以从 post save 中间件执行 mongoose 更新吗?
【发布时间】:2019-01-31 01:19:43
【问题描述】:

是否可以从save mongoose 中间件的帖子中更新文档?因为它不适合我。

我尝试过不同的方法。

方式一:

QuoteSchema.post('save', function(doc) {
if (doc.quoteString) {
    return;
}
this.quoteString = doc.quoteNumber + "";
this._doc.quoteString = doc.quoteNumber + "";
// update the record with quoteString 
this.update({ _id: this.id }, this, { new: true }, function(err, result) {
    if (!err) {
        console.log("Document Updated");
    }
});
    console.log('post save', doc.quoteString);
});

方式2:因为里面包含了保存的对象id所以直接试了。

QuoteSchema.post('save', function(doc) {
if (doc.quoteString) {
    return;
}
this.quoteString = doc.quoteNumber + "";
this._doc.quoteString = doc.quoteNumber + "";
enter code here
// update the record with quoteString 
this.update(function(err) {
    if (!err) {
        console.log("Document Updated");
    }
});
    console.log('post save', doc.quoteString);
});

方式3:

QuoteSchema.post('save', function(doc) {
if (doc.quoteString) {
    return;
}
var _quoteString = doc.quoteNumber+"";

this.update({ _id: doc._id }, { $set: { "quoteString": _quoteString } }, function(err) {
    if (!err) {
        console.log("Document Updated");
    }
});
console.log('post save', doc.quoteString);
});

这些方法都不适合我。

我所要做的就是在保存后更新 QuoteNumber 字段。 QuoteNumber 是从需要数字字段的猫鼬自动增量生成的。我还在 quoteString 字段中保存了 quoteNumber 的字符串版本,以便在 UI 中,我可以在自动完成中执行正则表达式搜索。由于正则表达式不适用于数字类型。

任何建议都会有所帮助。谢谢。

【问题讨论】:

    标签: node.js mongodb mongoose middleware mongoose-schema


    【解决方案1】:

    只需将自动增量字段设为虚拟,您就不必担心保存后挂钩...

    const QuoteSchema = new Schema(
      {
        quoteNumber: { type: Number },
        quoteString: { type: String },
      },
    );
    
    QuoteSchema.virtual('quote').set(function(value) {
      this.quoteNumber = Number(value);
      this.quoteString = String(value);
    });
    
    QuoteSchema.virtual('quote').get(function() {
      return this.quoteNumber;
    });
    

    设置:

    QuoteSchema.plugin(autoIncrement.plugin, { model: 'Quote', field: 'quote' });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-26
      • 2016-02-05
      • 2014-10-27
      • 1970-01-01
      相关资源
      最近更新 更多