Hi,
I am using a function in scheduled trigger which in turn uses updateMany() method to update the documents based on certain criteria.
exports = async function () {
const collection = context.services
.get(cluster)
.db("scheduler")
.collection("schedules");
const doc = await collection.updateMany(
{
status: "processing",
$expr: {
$gt: [{ $subtract: ["$$NOW", "$scheduleDate"] }, 30 60 1000]
}
},
{
$set: { status: "waiting" }
}
);
};
I want to log the documents before update. Can somebody help me with that?
Thanks
1 Like
MaBeuLux88
(Maxime Beugnet)
June 16, 2022, 7:24pm
2
Hi @manasa_pradeep and welcome in the MongoDB Community !
You can use console.log(X)
and the helpers EJSON.stringify(doc)
or JSON.stringify(doc)
.
Don’t forget to resolve the promise with the toArray()
.
Note that you actually have an alternative in the above link with items.forEach(console.log)
.
Cheers,
Maxime.
1 Like
Thanks, that worked:)
Now that I found the records, can I modify each item to update the status field to wait?
exports = async function () {
const collection = context.services
.get("Cluster0")
.db("test")
.collection("tests3");
const query = {
status: "processing",
$expr: {
$gt: [{
$subtract: ["$$NOW", "$scheduleDate"]
}, 30 * 60 * 1000]
}
};
const projection = {};
const readRecords = await collection.find(query, projection)
.toArray()
.then(items => {
console.log(`Successfully found ${items.length} documents.`)
console.log(JSON.stringify(items));
})
.catch(err => console.error(`Failed to find documents: ${err}`))
}
MaBeuLux88
(Maxime Beugnet)
June 17, 2022, 8:55pm
4
It should be an updateMany(X), no ?
Same query you already have and update = {$set: {status: "wait"}}
See the doc here:
Can I use findandModify() method?
MaBeuLux88
(Maxime Beugnet)
June 17, 2022, 9:08pm
6
findAndModify only finds and modifes a single doc.
Also apparently it’s not supported in App Services Functions.
Can you please help me with one more question?
I want to create a trigger that should fire when an insert happens to the nested column. Basically, it is an update to an existing document. How can I achieve that? I need to post the entire document to the HTTP end point. Thanks
MaBeuLux88
(Maxime Beugnet)
June 22, 2022, 12:42am
9
Using a MongoDB App Services Trigger, you can filter on update operation on a given collection. Then if you want to listen to just an update on a particular fields, you can check for the existance of that field ($exists) in the updateDescription of that update event.
Check the doc for triggers here . And especially you have exactly this exemple in the doc here .
Cheers,
Maxime.
system
(system)
Closed
December 13, 2022, 5:30am
10
This topic was automatically closed after 180 days. New replies are no longer allowed.