Auto populate date in MongoDB on insert

后端 未结 4 1295
说谎
说谎 2021-01-05 03:54

MongoDB provides a way to update a date field by the system on update operations: https://docs.mongodb.com/manual/reference/operator/update/currentDate/. Is there any equiva

4条回答
  •  长情又很酷
    2021-01-05 04:18

    If you want to populate this value when running it in the server side, and are concerned about it being passed by the client, you can add properties to the data object that is being used in the insert statement only when it will be saved. This way, you can guarantee that it will be added every time with the server's date, not the client's:

    Client side

    ...
    let data = { info1: 'value1', info2: 'value2'}
    someApi.addInfo(data);
    ...
    

    Server side

    function addInfo(data){
        ...
        data['creationDate'] = new Date();
        db.collection.insertOne(data);
        ...
    }
    

    Result will be:

    {
        info1: 'value1', 
        info2: 'value2',
        creationDate: ISODate("2018-09-15T21:42:13.815Z")
    }
    

    If you are passing multiple values for insertion (using insertMany) you have to loop over the items and add this property for all of them.

    You can also use this approach when updating documents if for some reason you can't use the $currentDate operator, just be sure you are not replacing any existing properties in the data passed to mongodb.

提交回复
热议问题