【问题标题】:Can I push to a nested array without knowing whether that array already exists?我可以在不知道该数组是否已经存在的情况下推送到嵌套数组吗?
【发布时间】:2017-10-06 22:47:08
【问题描述】:

我有一个结构如下的数据模型:

{
    "_id": "1234abcd",
    "name": "The Stanley Parable"
    "notes": [
        {
            "_id": "5678efgh",
            "content": "Kind of a walking simulator."
        },
                    {
            "_id": "5678efgh",
            "content": "Super trippy."
        },
    ]
}

我正在使用 C# 的 mongo 驱动程序与 .NET Core 中的此模型进行交互。我正在尝试为特定游戏添加新注释 - 不一定确定该游戏已经有任何注释。这是我能够找到的添加到嵌套列表的内容:

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);

但我的问题是,只有在游戏模型上已有“笔记”元素时才有效。我可以在制作原始游戏时添加一个空数组,但更改架构似乎不太灵活(即,如果我向现有数据添加注释怎么办)。

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'

【问题讨论】:

    标签: c# mongodb .net-core


    【解决方案1】:

    所以我最终找到了解决方案。

    首先,.Push() 确实按我的预期工作。如果数组不存在,它创建一个数组。

    我的实际问题与我使用的 C# 模型有关。以前:

    public class Mongo_VideoGame
    {
        [BsonId]
        [BsonRepresentation(BsonType.ObjectId)]
        public string Id { get; set; }
    
        [BsonElement("name")]
        public string Name { get; set; }
    
        [BsonElement("notes")]
        public List<Mongo_Note> Notes { get; set; }
    
    }
    

    但是由于它找到的文档上没有注释,所以我基本上是在尝试插入到 null 注释数组中。因此,为了解决这个问题,我为Notes 设置了默认值,以便可以将其推入。像这样:

    public class Mongo_VideoGame
    {
        [BsonId]
        [BsonRepresentation(BsonType.ObjectId)]
        public string Id { get; set; }
    
        [BsonElement("name")]
        public string Name { get; set; }
    
        [BsonElement("notes")]
        public List<Mongo_Note> Notes { get; set; } = new List<Mongo_Note>();
    
    }
    

    添加到现有数组和如果数组不存在则创建数组的情况现在都有效。

    【讨论】:

    • 定义存储不会像您发现的那样分配存储。使用 DI 容器时,需要移动硬连线的新列表。也许对于构造函数来说,基于构造函数的注入是相当普遍的。
    猜你喜欢
    • 2021-07-02
    • 1970-01-01
    • 2013-07-18
    • 2015-08-14
    • 1970-01-01
    • 1970-01-01
    • 2012-05-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多