簡體   English   中英

如何自動更新mongodb字段

[英]how to auto update mongodb field

我有一個Category架構,我想當children字段更改時檢查其長度,如果長度等於0,則has_children應該為false ,而相反。

這是我的模型:

const category_item = new mongoose.Schema({

   //...other fields...,
   children: { type: Array, required: true, default: [] }
   has_children:  // if children length equal to 0 get false and opposite     
});

保持

const category_item = new mongoose.Schema({

    ...anotherFields...,
    children : {type : Array , required : true , default : []}
    has_children : {type: Boolean}
});

並添加一個預保存鈎

category_item.pre('save', function(next) {
    if (this.children && this.children.length > 0) {
        this.has_children = true;
    } else {
        this.has_children = false;
    }
    next();
});

參考: http : //mongoosejs.com/docs/middleware.html

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM