使用MongoDB和C#的FindOne()时,有没有办法忽略对象中找不到的字段?
EG,示例模型。
public class UserModel
{
public ObjectId id { get; set; }
public string Email { get; set; }
}
现在我们还在MongoDB集合中存储密码,但不想将其绑定到上面的out对象。当我们这样做的时候,
var query = Query<UserModel>.EQ(e => e.Email, model.Email);
var entity = usersCollection.FindOne(query);
我们收到以下错误
Element 'Password' does not match any field or property of class
反正有没有告诉Mongo忽略它与模型不匹配的字段?
是。只需使用UserModel
属性装饰你的BsonIgnoreExtraElements
类:
[BsonIgnoreExtraElements]
public class UserModel
{
public ObjectId id { get; set; }
public string Email { get; set; }
}
顾名思义,驱动程序会忽略任何额外的字段而不是抛出异常。更多信息在这里 - Ignoring Extra Elements。
另一种可能的解决方案是为此注册一个约定。
这样,我们就不必使用[BsonIgnoreExtraElements]注释所有类。
在创建mongo客户端时,请设置以下内容:
var pack = new ConventionPack();
pack.Add(new IgnoreExtraElementsConvention(true));
ConventionRegistry.Register("My Solution Conventions", pack, t => true);
是。另一种方式(而不是编辑你的模型类)是使用RegisterClassMap
与SetIgnoreExtraElements
。
在您的情况下,只需在初始化驱动程序时添加此代码:
BsonClassMap.RegisterClassMap<UserModel>(cm =>
{
cm.AutoMap();
cm.SetIgnoreExtraElements(true);
});
您可以在此处阅读有关使用类映射忽略额外元素的更多信息 - Ignoring Extra Elements。