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}});
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`);
});
}
});
};
Product Schema
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 );
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.