【问题标题】:how to auto update mongodb field如何自动更新mongodb字段
【发布时间】:2017-02-09 21:21:28
【问题描述】:

我有一个 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     
});

【问题讨论】:

  • has_children 是否可能等于 true,然后等于 false?如果没有,我会说在创建新用户时将 has_children 设置为 false,然后当您添加孩子或创建具有孩子的新用户时将 has_children 设置为 true。

标签: javascript node.js mongodb mongoose database


【解决方案1】:

保持

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-09
    • 1970-01-01
    • 2017-09-09
    相关资源
    最近更新 更多