Logging the data

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

Hi @manasa_pradeep and welcome in the MongoDB Community :muscle: !

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.

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}`))



}

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?

findAndModify only finds and modifes a single doc.

Also apparently it’s not supported in App Services Functions.

Thanks. That clarifies.

1 Like

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

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.