ochero
ochero

Reputation: 917

Setting a default DateTime.Now value to save to MongoDB when Document is saved

I am very new to C#, having come from the ruby world, the ruby mongodb driver provided a created_at and updated_at field for all documents on saving and updating. Unfortunately after searching online it doesnt seem like this is a common thing in c#.

I would like to know how would I default a documents CreatedAt field to Time.Now when persisting?

using System;
using System.Collections.Generic;
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
using MongoDB.Driver;

namespace MongoDBConsole
{
    class Program
    {
        public static void Main(string[] args)
        {
            var client = new MongoClient("mongodb://localhost:27017");
            var database = client.GetDatabase("mongodb_console");
            var collection = database.GetCollection<Person>("person");
            var person = new Person
            {
                Name = "John Doe",
                Age = 25
            };
            collection.InsertOne(person);

        }
    }

    class Person
    {
        public string Name { get; set; }
        [BsonIgnoreIfNull]
         public int? Age { get; set; }
        [BsonDefaultValue(DateTime.Now)] // <-- this errors out
        private DateTime CreatedAt { get; set; }
    }
}

Edit:

My purpose for asking the question is to prevent myself from having to add a CreatedAt field every time I instantiate a new Person class object. CreatedAt should be automatically set whenever the Person class is persisted to MongoDB. One could easily set it every time a document is saved, but that's not very DRY. I am hoping to duplicate functionality that exists in another programming language.

Upvotes: 4

Views: 5601

Answers (2)

ochero
ochero

Reputation: 917

Came across this today,

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using MongoDB.Bson.Serialization.Attributes;

namespace NotebookAppApi.Models
{
    public class Note
    {
        [BsonId]
        public string Id { get; set; }
        public string Body { get; set; } = string.Empty;
        public DateTime UpdatedOn { get; set; } = DateTime.Now;
        public DateTime CreatedOn { get; set; } = DateTime.Now;
        public int UserId { get; set; } = 0;
    }
}

per the following blog

Using MongoDB .NET Driver with .NET Core WebAPI

Upvotes: 2

Abhilash Ravindran C K
Abhilash Ravindran C K

Reputation: 1856

Following code will be helpful to you,

var person = new Person
            {
                Name = "John Doe",
                Age = 25,
                CreatedAt = DateTime.Now
            };

Set CreatedAt property to DateTime.Now also.

Upvotes: 1

Related Questions