尝试从 Heroku 上托管的 NodeJS 应用程序连接到 MongoDB 云上的 mongodb。使用 mongodb ^3.2.3 和 MongoDBClient,在我的机器上本地运行很好,但在部署到 Heroku 后,得到上面的错误:“MongoError: MongoClient must be connected before call MongoClient.prototype.db”
const uri = "mongodb+srv://myuser:mypass@mongodbcluster/test?retryWrites=true";
const client = new MongoClient(uri, { useNewUrlParser: true });
client.connect(err => {
db = client.db("collection"); // <-- this is where it fails
...
Run Code Online (Sandbox Code Playgroud) 在我的一个应用程序中,除了在UserStore中创建新用户外,我还重写了Asp Core Identity UserManager的CreateAsync-在单独的统计信息表中(在不同的dbcontext上)创建新行。问题是,我希望将这两个操作都在事务内触发,这样,如果一个操作失败-另一个则不提交。这是代码:
public override async Task<IdentityResult> CreateAsync(TUser user, string password)
{
// We need to use transactions here.
var result = await base.CreateAsync(user, password);
if (result.Succeeded)
{
var appUser = user as IdentityUser;
if (appUser != null)
{
// create user stats.
var userStats = new UserStats()
{
ActionsCount = 0,
EventsCount = 0,
FollowersCount = 0,
ProjectsCount = 0,
UserId = appUser.Id
};
_ctx.UserStats.Add(userStats);
await _ctx.SaveChangesAsync();
}
}
return result;
}
Run Code Online (Sandbox Code Playgroud)
事情是,我不知道如何设置这样的事务,因为TransactionScope似乎还不是.Net Core的一部分(?),并且当前使用HttpContext.GetOwinContext()获取base.CreateAsync()的当前作用域DbContext并不由于HttpContext似乎缺少此方法,因此无法工作(引用其他堆栈溢出答案中所暗示的Microsoft.Owin.Host.SystemWeb或Microsoft.AspNet.WebApi.Owin都行不通-两者均与.netcore不兼容)。有什么帮助吗?