gpt4 book ai didi

node.js - Mongodb 查找然后更新

转载 作者:可可西里 更新时间:2023-11-01 10:28:17 25 4
gpt4 key购买 nike

我想运行一个查询,获取所有“事件”字段为真的文档,并对它们运行一个自定义函数,检查文档中的“日期”字段是否超过 10 天。如果它们都为真,那么它将使事件字段为假。

这是我当前代码的样子:

db.ad.find( { $and : [ // Check if active is true and the $where clause also equals to true
{ 'active' : true
},
{ '$where' : function() { // Custom compare function
var date = new Moment(this.date); // gets the date from the current document
var date2 = new Moment();
return Math.abs(date.diff(date2, 'days')) > 10;
}
}
]},
function(err, result) {
// How to update the document here?
}
);

谁能告诉我如何在查找查询后更新文档?

最佳答案

使用 update() 方法与 $set 修饰符运算符更新事件字段。与更新查询对象一样,您可以通过从日期中减去十天来将日期对象设置为十天前:

var d = new Date();
d.setDate(d.getDate() - 10);
var query = { /* query object to find records that need to be updated */
"active": true,
"date": { "$lte": d }
},
update = { /* the replacement object */
"$set": {
"active": false
}
},
options = { /* update all records that match the query object, default is false (only the first one found is updated) */
"multi": true
};

db.ad.update(query, update, options, callback);

-- 编辑 --

使用 momentjs 库,获取 10 天前的日期可以很简单(使用 add() 方法)

d = moment().add(-10, 'days');

或使用 subtract() 方法

d = moment().subtract(10, 'days');

关于node.js - Mongodb 查找然后更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31120111/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com