问题描述
在我们的应用程序中,我们有一个链接到mongoDB数据库的用户模型.我的问题是关于仅修改给定用户数据中键/值对中的一个值(当然使用用户ID).
In our app we have a user model linked to a mongoDB database. My question is about modifying only a value from key/value pair inside a given user data (of course using the User ID).
这是我的简单模型:
public class User
{
[BsonId]
public string Id { get; set; }
public string email { get; set; } = string.Empty;
public bool hasAcceptedTerms { get; set; } = false;
public int state { get; set; } = 0;
public int UserId { get; set; } = 0;
public IList<UserFile> SubmittedFiles { get; set; }
}
public class UserFile
{
public int fileID { get; set; }
public bool hasFile { get; set; }
}
在我们的应用中,首次验证用户身份后,我们使用以下方法在Mongo数据库中创建其条目
On our app, after authenticate the user for the first time, we create his entry in the Mongo Database using
public async Task AddUser(User item)
{
await _context.Users.InsertOneAsync(item);
}
首次登录后,我们要更新他接受条款的事实:通过这样做,我们希望将hasAcceptedTerms
更改为true
并将state
键从0移到1
.
After his first login we want to update the fact he accepted Terms: by doing so we want to change hasAcceptedTerms
to true
and move the state
key from 0 to 1
.
目前,在我们的存储库中,我们有类似的东西:
For the moment in our Repository we have something like:
public async Task<UpdateResult> UpdateUser(string id, User item)
{
return await _context.Users
.ReplaceOneAsync(n => n.Id.Equals(id)
, item
, new UpdateOptions { IsUpsert = true });
}
但是这样做,我们必须提供与我们的模型相对应的完整项目.
But by doing so we must provide a full item corresponding to our model.
我找不到创建可以使用的函数的任何方法:
I don't find any way to create a function which I could use like:
UdateUserData(string id, string data, bool newvalue);
例如,调用UpdateUserData('user1objectidhash', 'hasAcceptedTerms', true)
会为由其ObjectID ID标识的用户修改正确的值.
For example call UpdateUserData('user1objectidhash', 'hasAcceptedTerms', true)
would modify the correct value for the user identified by his ObjectID Id.
- 第一个问题:是否将
data
键入为string
是一个好主意/独特的解决方案??通过将数据键键入为字符串,我发现函数调用并不优雅. li> - 第二个:我不知道newvalue的类型是什么,因为它取决于我要修改的数据.我可以从模型中检测到它吗?
- 第3名:我不知道可以处理此更新的正确的Mongo.Driver函数.
- First problem: is typing
data
asstring
a good idea/unique solution? I don't find my function call being elegant by typing the data key as a string. - 2nd: I don't know what will be the type of newvalue because it will depend on what is the data I want to modify. Can I detect it from model?
- 3rd: I don't know the correct Mongo.Driver function which can process this update.
能给我一些提示和提示吗?
Could you give me some cues and tips?
推荐答案
如果您只想更新整个对象,而不是某些属性,则可以执行以下Update
命令:
If you just want to update not whole object, but some properties it's possible to do this Update
command:
collection.UpdateOneAsync(x=>x.Id ==id,
Builders<User>.Update.Set(u=>u.hasAcceptedTerms, false)
.Set(u=>u.state, 1));
我认为,该集合是您的IMongoCollection<User>
,您所说的是_context.Users
I assume, that collection is your IMongoCollection<User>
, that you mean with _context.Users
这篇关于MongoDB和Asp Core仅更新一个键:值对而不是整个模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!