我在向我的 mongo 文档添加子对象后遇到了问题。查询不再返回结果,即使我已向模型添加对象以存储新的子对象也是如此。
我相信问题在于将子对象的类添加到对象模型中。我似乎在网上任何地方都找不到任何参考资料,所以也许我搜索错了东西?
Mongo 元素如下所示:
{
_id: [id],
Name: "Paul",
Phone1: {
Name: "Work",
Number: "15551234567"
},
Phone2: {
Name: "Work",
Number: "15551234567"
}
}
在 C# 中,我的模型如下所示:
public class PersonModel {
[BsonId]
public ObjectId _Id { get; set; }
public string Name { get; set; }
public Phone Phone1 { get; set; }
public Phone Phone2 { get; set; }
}
public class Phone {
public string Name { get; set; }
public string Number { get; set; }
}
我的查询如下所示:
public async Task<List<PersonModel>> GetPerson(string name)
{
var people = new List<PersonModel>();
var allDocuments = await PersonCollection.FindAsync(
ds => ds.Name == name);
await allDocuments.ForEachAsync(doc => people.Add(doc));
return people;
}
如能提及工作实例,将不胜感激。
谢谢你的关注。
上面的实现是正确的。经过几个小时的故障排除,事实证明我的数据库中没有我正在查询的数据点。难以置信。
如果其他人在挣扎,我还找到了本指南,它确认我正在正确处理子对象:https://www.codementor.io/pmbanugo/working-with-mongodb-in-net-1-basics-g4frivcvz