使用node-cron用猫鼬更新多个文档 [英] Update multiple documents with mongoose using node-cron

查看:92
本文介绍了使用node-cron用猫鼬更新多个文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用node-cron用猫鼬更新多个文档.我要完成的工作是创建的所有文档(例如7月1日)在30天后将处于非活动状态.

I'm trying to update multiple document with mongoose using node-cron. What I'm trying to accomplish is all documents that was created, let's say, July 1, will have an status of inactive after 30 days.

我设法使用下面的代码更新多个文档,但是我不知道如何使用日期小于当前日期的产品更新多个文档:

I manage to update multiple document using the code below but I don't know how to update multiple documents with products which date is less than the current date:

我知道如何使用小于当前日期的产品列表,但是我不知道如何将此逻辑应用于下面的代码-

I know how to get the list of product that is less than the current date using but I don't know how to apply this logic to the code below -

let currentDate = new Date();
let query = Product.find({ dateCreated: {$lt: currentDate}});

代码与我要完成的任务无关.这是一个样本 该代码将每10秒更新多个文档.

Code is unrelated to what I'm trying to accomplish. This is a sample code that will update multiple documents every 10 seconds.

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中的多个文档吗?如果我的问题令人困惑,请原谅我.

This is the only way I know to update multiple document in mongoose. So is there other way to update multiple document in mongoose after 30 days of creation using mongoose and node-cron? Pardon me if my question is confusing.

推荐答案

在这里您可以找到完整版本的代码.

Here you go the full version of code.

这里您无需进行多个查询,例如先选择全部 当前日期符合您条件的产品.原因是 您可以在更新产品本身的同时进行.

Here you no need to make multiple queries, like first selecting all the products whose currentdate has matched your criteria. Cause that you can do while updating the products itself.

const mongoose = require('mongoose');
const Product = require('../model/product');
const cron = require('node-cron');

cron.schedule('*/10 * * * * *', function() {
    let productArray = ['Bacon', 'Apple', 'Fork', 'Beans'];
    updateAllProducts(productArray, (err, res) => {
        if (err)
            //error handle, you can log here
        else
        //success handle, you can log here
    })
});

let updateAllProducts = (productArray, callbackFn) => {
    let randomNumber = Math.floor(Math.random() * (999 - 1 + 1));
    description = `Random description generate every 10 seconds: ${randomNumber}`;
    Product.update({
        name: {
            $in: productArray
        },
        dateCreated: {
            $lt: currentDate
        }
    }, {
        description: description
    }, {
        multi: true
    }, (err, res) => {
        if (err) {
            callbackFn(err, null)
        } else {
            callbackFn(null, err);
        }

    });

};

在这种情况下,您还可以记录Db更新是成功还是失败.因此,可以更好地控制代码.而不是循环进行多个呼叫.那将是非常耗时且容易出错的.

In this case you can also log if Db update was failure or success. So there is better control over code. Rather than making multiple Calls in loop. That would be really time consuming and error prone.

希望这会有所帮助!

这篇关于使用node-cron用猫鼬更新多个文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆