MongoDB and Asp Core update only a key: value pair instead of whole model

社会主义新天地 提交于 2019-12-25 18:35:11

问题


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?


回答1:


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));

I assume, that collection is your IMongoCollection<User> , that you mean with _context.Users



来源:https://stackoverflow.com/questions/41493327/mongodb-and-asp-core-update-only-a-key-value-pair-instead-of-whole-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!