How to set field validation in mongodb atlas function for crud operation

I am creating a MongoDB atlas function for an insert operation and I want to know how to validate the data before the insert operation. One more thing I am having an issue with the date as I am saving some fields with a date but the format I want to save is 2023-03-03T00:00:-0.000+00:00 but the date is saving like this 2023-03-03T10:30:30.734+00:00 with new Date().

this function moment(new Date()).format("YYYY-MM-DD") is giving the format I need but Mongodb taking it as a string and saving it as a string.
But MongoDB takes new Date() as a date but the date is coming with timezones that I don’t need.

So I want to know how to make the date as date not as a string in the MongoDB atlas function

Here is my sample function:

import moment from "moment";
exports = function () {
  context.values.get("somecluster");
  const mongodb = context.services.get("mongodb-atlas");
  const collection = mongodb.db("some database").collection("collection");
   collection .insertOne({
  	new_date: moment(new Date()).format("YYYY-MM-DD"),
  	next_date: new Date(),
  	createdAt: new Date(),
  	lastUpdatedAt: new Date(),
  });
	return {
		status: "ok",
	};

};

Hello :wave: @Zubair_Rajput,

Welcome back to the MongoDB Community forums :sparkles:

Before inserting or updating data using App Services, you can validate the documents by enforcing the schema. Additionally, it’s also possible to validate any modifications made to the documents by specifying a validation expression in the schema.

To enforce a schema in Atlas App Services, you can follow the six-step procedure provided.

You can insert the date in your desired format by executing the following command:

exports = function () {
    context.services.get("mongodb-cluster").db("test_db").collection("test_coll").insertOne({
  	new_date: new Date("2023-05-02"),
  	next_date: new Date(),
  	createdAt: new Date(),
  	lastUpdatedAt: new Date(),
  });
	return {
		status: "ok",
	};
};

It will return the following output:

Image


However, just for my understanding, can you explain the reason for the exact requirement for the date field and what further operations you expect to perform?

Can you please elaborate more, on what you mean by the above statement?

Typically mongosh wraps the Date object with the ISODate helper and the ISODate is in UTC format.

Best,
Kushagra

Hey @Kushagra_Kesav To enforce a schema in Atlas App Services, you can follow the six-step procedure provided.
This procedure only validate the existing documents into our collection but didn’t validate the document before insertion. Please help me that how can I enforce a schema on insertOne(), insertMany(), updateOne() and updateMany() methods. Thanks