I have a data model that's structured something like this:
{
"_id": "1234abcd",
"name": "The Stanley Parable"
"notes": [
{
"_id": "5678efgh",
"content": "Kind of a walking simulator."
},
{
"_id": "5678efgh",
"content": "Super trippy."
},
]
}
I'm using the mongo driver for C# to interact with this model in .NET Core. I'm trying to add a new note to a particular game -- without necessarily being sure that there are any notes on that game already. This is what I've been able to find for adding to a nested list:
var filter = Builders<Mongo_VideoGame>.Filter.Eq("Id", id);
var update = Builders<Mongo_VideoGame>.Update.Push<Mongo_Note>(v => v.Notes, mongoNote);
var editedGame = _context.VideoGames.FindOneAndUpdate(filter, update);
But my problem is that this only works if there's already a "notes" element on the game model. I could just add an empty array when I make the original game, but that seems less flexible to changing the schema (i.e. what if I was adding notes to existing data).
An exception of type 'MongoDB.Driver.MongoCommandException' occurred in MongoDB.Driver.Core.dll but was not handled in user code: 'Command findAndModify failed: The field 'notes' must be an array but is of type null in document'