setInterval() is not wotking in azure microsoft - node.js

setInterval() is not working in Azure Microsoft. I need a function to do the task every month or week? so what can I do? the code is working without azure but with azure not working?
nodejs code :
setInterval(async function check() {
if ((date.getDate() == 8) && (date.getHours() == 18) && (date.getMinutes() == 39) && (date.getSeconds() == 00)) {
await Drawings.find({}).then((data) => {
data.sort(function (a, b) {
return b.stars - a.stars;
})
if (data == null) {
return;
}
AllDrawings.updateMany({
"potmCurrentWinner": true
}, {
$set: {
"potmCurrentWinner": false
}
}, async function (err) {
if (err) {
return;
}
// move the drawing to potm
await AllDrawings.updateOne({
"DrawingName": data[0]['DrawingName']
}, {
$set: {
"potmCurrentWinner": true,
"potm": true
}
}, async function (err) {
//move file
await User.updateOne({
userName: data[0].Drawer
}, {
$inc: {
stars: 25
}
})
console.log("done3");
await User.updateOne({
userName: data[0].Drawer
}, {
$inc: {
drawingOfTheMonth: 1
}
});
//delete all drawwing the u give star
await User.updateMany({}, {
$set: {
drawingThatGotYourStar: []
}
});
await Drawings.deleteMany({});
console.log("done4");
});
});
})

you have missing code here, the brackets from the initial condition and the closing parenthesis for the setInterval function call

Related

can't use the results of a mongoose query when called from another function

I'm writing a blog engine using express, and ran into a problem when trying to run a mongoose query through a function:
What I'm trying to do is to obtain a variable that contains the next and previous blog posts by id, to do that I wrote this function:
middleware.getAdjacentPosts = async function(_id) {
var adjacentPosts = {}
await Post.findOne({ _id: { $gt: _id } }).sort({ _id: 1 }).exec(async function(err, nextPost) {
if (err) {
console.log(err)
} else {
if (nextPost == null) {
adjacentPosts.nextPost = false;
} else {
adjacentPosts.nextPostUrl = nextPost.slug;
adjacentPosts.nextPostTitle = nextPost.title;
}
await Post.findOne({ _id: { $lt: _id } }).sort({ _id: -1 }).exec(
async function(err, previousPost) {
if (err) {
console.log(err.message);
} else {
if (previousPost == null) {
adjacentPosts.previousPost = false;
} else {
adjacentPosts.previousPostUrl = previousPost.slug;
adjacentPosts.previousPostTitle = previousPost.title;
}
console.log(adjacentPosts)
return adjacentPosts
}
})
}
})
}
Before returning, I can see the variable completed with what I need through the console.log. The problem I have is that when I try to execute the function, the receiving variable is empty. This would be executed in the get route for a post, like the following:
Router.get("/posts/:slug", async function(req, res) {
await Post.findOne({ slug: req.params.slug }).populate('categories').populate('comments').exec(async function(err, foundBlog) {
if (err) {
console.log(err.message)
} else {
var posts = {}
posts = await middleware.getAdjacentPosts(foundBlog._id)
console.log(posts)
res.render("frontoffice/post", {
blog: foundBlog,
postUrl: req.params.slug,
adj: posts,
reCaptchaSiteKey: process.env.CAPTCHA_SITE_KEY
})
}
})
})
Any clues of what I might be doing wrong?
As #LucaKiebel suggests, you will need to return the results from your findOnes:
middleware.getAdjacentPosts = async function(_id) {
var adjacentPosts = {};
return await Post.findOne({ _id: { $gt: _id } })
.sort({ _id: 1 })
.exec(async function(err, nextPost) {
if (err) {
console.log(err);
} else {
if (nextPost == null) {
adjacentPosts.nextPost = false;
} else {
adjacentPosts.nextPostUrl = nextPost.slug;
adjacentPosts.nextPostTitle = nextPost.title;
}
return await Post.findOne({ _id: { $lt: _id } })
.sort({ _id: -1 })
.exec(async function(err, previousPost) {
if (err) {
console.log(err.message);
} else {
if (previousPost == null) {
adjacentPosts.previousPost = false;
} else {
adjacentPosts.previousPostUrl = previousPost.slug;
adjacentPosts.previousPostTitle = previousPost.title;
}
console.log(adjacentPosts);
return adjacentPosts;
}
});
}
});
};
A potential improvement, since you are using async/await anyway, might be to get rid of the callbacks:
middleware.getAdjacentPosts = async function(_id) {
var adjacentPosts = {};
try {
const nextPost = await Post.findOne({ _id: { $gt: _id } }).sort({ _id: 1 });
if (nextPost == null) {
adjacentPosts.nextPost = false;
} else {
adjacentPosts.nextPostUrl = nextPost.slug;
adjacentPosts.nextPostTitle = nextPost.title;
}
const previousPost = await Post.findOne({ _id: { $lt: _id } }).sort({ _id: -1 })
if (previousPost == null) {
adjacentPosts.previousPost = false;
} else {
adjacentPosts.previousPostUrl = previousPost.slug;
adjacentPosts.previousPostTitle = previousPost.title;
}
console.log(adjacentPosts);
return adjacentPosts;
} catch (err) {
console.log(err);
}
};
``

Dynamodb record not updating through for loop

I'm currently using dynamoose for managing records in dynamodb.
from my client I'm receiving a collection of insiders
insiders: [
{ uid: '123', name: 'Insider A' },
{ uid: '456', name: 'Insider B' },
{ uid: '789', name: 'Insider B' }
]
and my lambda function receives the collection thru insiders variable and I loop in each records. Inside loop I update the position of the records
module.exports.reorder = async (event) => {
const klass = await getKlass.byEnv(process.env.STAGE, 'insider');
const req = event.body
var insiders = req.insiders;
try {
for (let [index, insider] of insiders.entries()) {
console.log("Insider: ", insider);
console.log("Index: ", index);
await klass.update({ uid: insider.uid }, {
$PUT: {
position: index += 1
}
}, { condition: 'attribute_exists(uid)' })
}
return successResponse.message();
} catch (err) {
console.log("===============");
console.error(err);
console.log("===============");
if (err && err.code == 'ConditionalCheckFailedException') {
return noRecord404.notFound();
}
}
}
this is working fine when I'm testing it in my local but when I deploy it to AWS Lambda It's not being updated. I also put console.log inside loop and I'm getting the printed log.

MongoDB, increment field with condition

Is it possible, using mongoose middleware, to increment two fields one with a condition and the other without? In this case i want to increment "stats.ratings" by one, if the user inserts an input greater than 0, else increment zero.
"stats.answered" always increments one
See code below
module.exports.updateStats = function (req, res) {
var rating = parseInt(req.body.rating, 10);
var wasRated;
if (rating > 0) {
wasRated = true;
} else wasRated = false
Collection.findOneAndUpdate({
_id: req.body._id
}, {
$cond: {
if: wasRated,
then: {
$inc: {
"stats.answered": 1,
"stats.ratings": 1
}
},
else: {
$inc: {
"stats.answered": 1,
"stats.ratings": 0
}
}
}
},
function (err, doc) {
if (err)
throw err;
res.status(200);
})
}
What you can do is this:
// define the default case
var update = {
$inc: {
"stats.answered": 1
}
};
if(parseInt(req.body.rating, 10) > 0) {
// override default in some cases
update = {
$inc: {
"stats.answered": 1,
"stats.ratings": 1
}
}
}
and then
Collection.findOneAndUpdate({
_id: req.body._id
}, update,
function (err, doc) {
if (err)
throw err;
res.status(200);
})
}

Async/await function yields on undefined

I'm having trouble with an async function. I'm making a query (using mongoose) to a mongodb and when I try to get the info back it yields undefined.
Here's my query to the db (nested within a function):
function kquery() {
Krakentick.findOne(
{
iname: 'btcusd',
n: { $lt: now }
},
'mk c n',
function(err, tick) {
if (err) {
return console.log(err);
} else {
return tick;
}
}
);
}
and here's my async/await function:
async function compare() {
var ktick = await kquery();
console.log(ktick);
}
compare();
These functions are both in the same file, and when I run it it gives me an 'undefined'.
While, when I just run the query function and puts up a console.log(tick) instead of the return tick, I get the correct information:
{ _id: 59d1199cdbbcd32a151dcf21,
mk: 'kraken',
c: 430900,
n: 1506875804217 }
I think, I'm messing up with the callback somewhere but I'm not sure where or how.
Here's the full file:
const mongo = require('mongodb');
const mongoose = require('mongoose');
mongoose.Promise = global.Promise;
const server = mongoose.connect('mongodb://localhost/cryptoCollection', {
useMongoClient: true
});
//Loading the mongoose schema:
const { Krakentick } = require('./kraken/model/krakenModel');
var now = Math.floor(new Date());
function kquery() {
Krakentick.findOne(
{
iname: 'btcusd',
n: { $lt: now }
},
'mk c n',
function(err, tick) {
if (err) {
return console.log(err);
} else {
return tick;
}
}
);
}
async function compare() {
var ktick = await kquery();
console.log(ktick);
}
compare();
Thanks in advance for your help!
Your kquery function must return the promise :
function kquery() {
return Krakentick.findOne(
{
iname: 'btcusd',
n: { $lt: now }
},
'mk c n',
function(err, tick) {
if (err) {
return console.log(err);
} else {
return tick;
}
}
);
}
Just posting the promesified kquery function for reference:
function kquery() {
return new Promise((resolve, reject) => {
Krakentick.findOne(
{
iname: 'btcusd',
n: { $lt: now }
},
'mk c n',
function(err, tick) {
if (err) {
reject(err);
} else {
resolve(tick);
}
}
);
});
}
The accepted answer was the one above although it had been discussed and documented previously in the comments by Mörre! I just wanted to leave it there in case it helps someone!
Thanks again for your valuable help!

How to update records on continues Hierarchy in mongoose?

I have a record in such a way like below
1)
{
"name":"A",
"parents":[ADMIN],
"childrens":[B,C,D]
}
2)
{
"name":"B",
"parents":[A],
"childrens":[D,K,L]
}
3)
{
"name":"C",
"parents":[B],
"childrens":[K,L]
}
4)
{
"name":"D",
"parents":[C],
"childrens":[L]
}
Here if a add a new record 'E' and will make 'C' as parent ,then the logic is the record 'E' should be added as child to the parent of 'C'i.e for 'B' and at the same time 'E' should also be added to parent of 'B'.This logic is quite confusing when i start to write code and complex too but i achieved up to some extent that i can make 'E' as a child of 'C' and also the parent of 'C' but not further.
My Code:
function (callback) {
var item = {'employee' : employee.manager };
Employeehierarchy.find(item).exec(function (err, employeeparent) {
if (employeeparent && employeeparent.length > 0) {
Employeehierarchy.update(
{ _id: employeeparent[0]._id},
{"$push": { "childrens": employee._id } }
).exec(function (err, managerparent) {
});
callback(err,employeeparent);
} else{
callback(err,employeeparent);
}
}
});
},
//Finding the parent record of the manager in hierarchy
function (employeeparent, callback) {
var item = {'employee' : employeeparent[0].parents };
Employeehierarchy.find(item).exec(function (err, managerparent) {
if (err) {
return res.status(400).send({ message: errorHandler.getErrorMessage(err) });
} else {
if (managerparent && managerparent.length > 0) {console.log(managerparent+'managerparent')
Employeehierarchy.update(
{ _id: managerparent[0]._id},
{"$push": { "childrens": employee._id } }
).exec(function (err, managerparent) {
});
callback(err,managerparent);
} else{
callback(err,managerparent);
}
}
});
}else {
callback();
}

Resources