2

So today I realized I have a problem with updating/pushing to an array. I have an array in a class that is just a auto property

public List<things> Things { get; set; }

This can get put in the database as null and if I later on need to write a query like

var query = Query.EQ("_id", something.Id);
var update = Update.Push("Things", thing.ToBsonDocument());

coll.Update(query, update);

I now have a problem because my update will throw an exception that I tried to push to a NULL array.

I solved this by just putting a private backer on the class

private List<things> _things = new List<things>();
public List<things> Things { get { return _things;} set { _things = value;} }

Now at least a new instance will have an empty array and someone would need to explicitly say

Things = null

But I was wondering is there a better way to solve this. Decorators? Mongo Index? something to say hey this field must ALWAYS be an array.

I've always been kind of dubious of auto properties and prefer using the private backer especially for non primitives. Just wondering if a more robust solutions exist that's built into the Mongo engine.

2 Answers 2

3

If you would prefer to use autoproperties you can simply have the constructor create the empty list.

public YourClass() 
{
   Things = new List<things>();
}

Then the auto property works simply and the only spot with any ugliness is the constructor.

This is What I do

Sign up to request clarification or add additional context in comments.

Comments

2

Also some convert script when you are starting your application is not a bad idea

<code>
var emptyInterUsers = db.List<UserEntity>(u => u.Interests == null);
if (emptyInterUsers.Any())
{
    foreach (var u in emptyInterUsers)
    {
        if (u.Interests == null)
        {
            var filter = db.F<UserEntity>().Eq(f => f.id, u.id);
            var update = db.U<UserEntity>().Set(f => f.Interests, new List<int>());
            var res = await db.UpdateAsync(filter, update);
        }
    }                   
}
</code>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.