首页 > 解决方案 > 无法使用 insertOneAsync 在 mongodb 中插入数据

问题描述

我想将数据插入到 mongodb 数据库中。它就像一种魅力,但我有一个无法插入数据库的集合,我不知道为什么。我确实是一样的。

这在这里不起作用

public async Task AddVerifyAsync(VerifyModel verifyModel)
{
       verifyModel.CreationDate = DateTime.Now;
       await _context.Verifies().InsertOneAsync(verifyModel);

}

我检查了多次,运行调试模式,检查模型等,都是绝对正确的。这是返回集合的方法:

public IMongoCollection<VerifyModel> Verifies()
{
     return _database.GetCollection<VerifyModel>("VerifyModel");
}

这些是有效的方法:

public async Task AddUserAsync(UserModel user)
{
       await _context.Users().InsertOneAsync(user);
}

集合返回器与上面的相同,但具有其他类型。我什至试图删除 DateTime 的东西。我也设置了_id之前给它的AddVerifyAsync方法。但我什至尝试禁用它。

_context是在构造函数中注入的依赖项。这是使用这两种方法的地方:

public async Task CreateUserAsync(UserModel user)
        {
            UserModel gotUser = await _userRepository.GetUserByEmailAsync(user.Email);
            //check if exists
            if (gotUser != null)
                throw new DataException();

            //set defaults and prevent, that the user tries to manipulate data
            user.Active = false;
            user.RegTimeStamp = DateTime.Now;
            user.AdminLevel = 0;
            user.OrganizationId = null;
            user.OrganizationAdminLevel = null;
            user.Password = BCrypt.Net.BCrypt.HashPassword(user.Password);
            user.Balance = 0f;
            user.ProfilePicture = "";
            //Add the user to the repo
            await _userRepository.AddUserAsync(user);
            VerifyModel verifyModel = new VerifyModel();
            verifyModel.UserId = user.Id;
            verifyModel.Id = ObjectId.GenerateNewId().ToString();
            //useractivation
            verifyModel.Type = 0;
            //insert the verifyuser in database
            await _verifyRepository.AddVerifyAsync(verifyModel);
            await _emailSenderService.SendMailAsync(user, EmailTemplate.RegisterMail, verifyModel.Id,
                "Herzlich Willkommen bei flundr. Nur noch ein Schritt!", user.Email);
        }

这里的验证模型没有插入到数据库中。

标签: c#mongodb

解决方案


推荐阅读