如何自动更新 mongodb 文档中的值

玛诺·普拉萨纳

我的猫鼬模式中有一个名为“active”的字段,我想知道是否有任何方法可以使特定文档中的每个日期过期,然后“active”字段将更改为false如果是这样,我该怎么做,最简单的方法是什么?否则,有什么推荐?

下面是我的架构;

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const schema = new Schema({

user_id: {
    type: String,
    required: true
},
firstName: {
    type: String,
    required: true
},
username: {
    type: String,
    required: true
},
email: {
    type: String,
    required: true
},
hash: {
    type: String,
    required: true
},
active: {
    type: Boolean,
},

role: {
    type: String,
    required: true
},
createdDate: {
    type: Date, 
    default: Date.now

}
});

schema.set('toJSON', { virtuals: true });

module.exports = mongoose.model('User', schema);
戈切夫

您可以使用 mongo 中的一项功能来实现这一点,该功能Change Streams允许您访问实时数据更改。您可以订阅单个集合或整个数据库的更改并对它们做出反应。您还可以过滤特定的更改或转换。对于你的情况,一个例子是这样的。

编辑:更改流实现仅适用于副本集。

const pipeline = [
  { $match: { expire_date: {$lt: Date.now()} } },
  { $set: { active: false } }
];

const collection = db.collection('user');
const changeStream = collection.watch(pipeline);
changeStream.on('change', next => {
  // process next document
});

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章