【发布时间】:2017-12-08 13:54:26
【问题描述】:
我正在尝试使用 node-cron 使用 mongoose 更新多个文档。我想要完成的是所有创建的文档,比如说,7 月 1 日,在 30 天后将处于非活动状态。
我设法使用下面的代码更新多个文档,但我不知道如何使用日期小于当前日期的产品更新多个文档:
我知道如何获取小于当前使用日期的产品列表,但我不知道如何将此逻辑应用于下面的代码 -
let currentDate = new Date();
let query = Product.find({ dateCreated: {$lt: currentDate}});
代码与我要完成的工作无关。这是一个样本 每 10 秒更新多个文档的代码。
const mongoose = require('mongoose');
const Product = require('../model/product');
const cron = require('node-cron');
cron.schedule('*/10 * * * * *', function(){
let productArray = ['Bacon', 'Apple', 'Fork', 'Beans'];
productArray.map(product => updateProduct(product));
});
let updateProduct = (name) => {
let randomNumber = Math.floor(Math.random() * (999 - 1 + 1));
let query = Product.findOne({name: name}).select({ 'name': 1 });
query.exec((err, product) => {
if(err) throw err;
if(product){
product.description = `Random description generate every 10 seconds: ${randomNumber}`;
product.save(err =>{
if(err) throw err;
console.log(`Successfully updated random description for: ${product.name}\n ${product.description}\n`);
});
}
});
};
产品架构
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const productSchema = mongoose.Schema({
name : String,
description : String,
status : String,
dateCreated : { type: Date, default: Date.now }, //
});
module.exports = mongoose.model( 'Product', productSchema );
这是我知道在猫鼬中更新多个文档的唯一方法。那么有没有其他方法可以在使用 mongoose 和 node-cron 创建 30 天后更新 mongoose 中的多个文档?如果我的问题令人困惑,请原谅我。
【问题讨论】:
-
你有没有试过这样的查询
Product.update({name : { $in : productArray }, dateCreated: {$lt: currentDate} }, {status : 'inactive' },{multi: true}, callbackfn()) -
哦,还没有。这是个好主意,但如果 productArray 是动态的呢?查询产品列表然后使用您提到的查询会给可能的应用程序带来沉重的负担吗?假设::: 获取产品列表(主查询),然后在找到产品列表后 - 将主查询的结果设置为 productArray 然后执行 subQuery(your query)?
-
你是不是想说,查询每个数组元素比一次查询要好。你误会了,我的朋友。原因如果您让猫鼬自己处理多重更新,它会比您尝试实现的更快。此外,您还循环调用了异步更新方法。所以你的代码也会很慢而且没有优化。
-
不客气,我已经添加了解决方案。这将是对 DB 的一次调用,可以灵活地在某一时刻记录事务状态。希望它能达到你的目的!
标签: node.js mongoose cron node-cron