How to update a subdocument in a mongoDB document with Findoneandupdateasync

Asked

Viewed 23 times

2

I’m trying to add a subdocument to a mongoDb document, but even looking at the previous posts I couldn’t find a solution. My classes

    public class UserClass
    {
        [BsonId]
        [BsonRepresentation(BsonType.ObjectId)]
        public string Id { get; set; }
        public string Name { get; set; }
        public string Email { get; set; }
        public string Password { get; set; }
        public string Secret { get; set; }
    
        public IEnumerable<UserNotes> Notes { get; set; }
        
    }

 public class UserNotes
    {
        [BsonId]
        [BsonRepresentation(BsonType.ObjectId)]
        public string Id { get; set; }
        public string IdUser { get; set; }
        public string Title { get; set; }
        public string Note { get; set; }

    }

In my service I have the following code:

 [HttpPost]
 public async Task<bool> UserAddNote(string IdUser, UserNoteDtoCreate note)
        {
            try 
            {
                 var user = new UserClass();
                 user =_Users.Find<UserClass>(user => user.Id == IdUser).FirstOrDefault();
                 if (user == null) 
                 {
                     return false;
                 }

                 var noteint = new UserNotes();
                 noteint = _mapper.Map<UserNotes>(note);

                 noteint.IdUser = IdUser;
                 noteint.Title = "title";
                
                var update = Builders<UserClass>.Update.Push(c => c.Notes, noteint);
                
                await _Users.FindOneAndUpdateAsync(c => c.Id == IdUser, update);


                
                return true;
            }
            catch (System.Exception)
            {
                
                throw;
            }

        }

When executing it does not return any error message, but it also does not add the note to the document. I’ve tried it this way:

var record = await _Users.FindOneAndUpdateAsync( 
                     Builders<UserClass>.Filter.Where(rec => rec.Id == IdUser),
                     Builders<UserClass>.Update.Set(rec => rec.$.Notes, noteint),
                     options : new FindOneAndUpdateOptions<UserClass>
                     {
                         ReturnDocument = ReturnDocument.After
                     }

                 );

This is the configuration of the api:

<ItemGroup>
    <PackageReference Include="MongoDB.Driver" Version="2.12.3" />
    <PackageReference Include="AutoMapper.Extensions.Microsoft.DependencyInjection" Version="8.1.1" />
    <PackageReference Include="AutoMapper" Version="10.1.1" />
    <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="3.1.16" />
  </ItemGroup>

Anybody got any ideas? Thank you

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.