C#mongoDB不会更新数据库

时间:2016-01-17 16:38:06

标签: c# arrays mongodb bson

我想在我的mongoDB集合中更新数组。发布新文档工作得很好,但它不会更新数组。我的文件结构是:

 var document = new BsonDocument
        {               
            { "post_title",  model.Title  },
            { "post_text",  model.Text  },
            { "post_author",  model.Author  },
            { "post_picture",  model.Picture  },
            { "post_comments",  new BsonArray()  },
        };

我的更新功能是:

[HttpPost]
    [Route("api/PostInfo/{Comment}")]
    public async Task Post(Comment comment)
    {
        try {
            BsonObjectId oldId = new BsonObjectId(new ObjectId(comment.id.ToString()));

            var mongoDbClient = new MongoClient("mongodb://127.0.0.1:27017");
            var mongoDbServer = mongoDbClient.GetDatabase("nmbp");
            var collection = mongoDbServer.GetCollection<PostInfo>("post");

            var filter = Builders<PostInfo>.Filter.Eq(e => e._id, oldId);
            var update = Builders<PostInfo>.Update.Push("post_comments", comment.comment);
            await collection.FindOneAndUpdateAsync(filter, update);
            var test = oldId.GetType();
        }
        catch
        {
        }
    }

调试时,我可以看到后置控制器被触发,注释值是正确的,但是当我查看数据库时,“post_comments”数组的值为空。 catch块中没有抛出错误。我做错了吗?

1 个答案:

答案 0 :(得分:0)

看起来问题出现在这一行:

var filter = Builders<PostInfo>.Filter.Eq(e => e._id, oldId);

正确的应该是这样的:

var filter = Builders<PostInfo>.Filter.Eq("_id", oldId);