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).
Here is my simple model:
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; }
}
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);
}
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);
For example call UpdateUserData('user1objectidhash', 'hasAcceptedTerms', true)
would modify the correct value for the user identified by his ObjectID Id.
- First problem: is typing
data
as string
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?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…