mongodb4.0支持事务了,mongoose也跟着支持了
发布于 7 年前 作者 lovegnep 31403 次预览 最后一次回复是 7 年前 来自 问答
但是不知道怎么用啊,在官方也没找到相关的demo,有人写过demo测试了吗?
更新下,在mongoose官网上找到了demo
http://thecodebarbarian.com/a-node-js-perspective-on-mongodb-4-transactions.html
自己写的demo如下:
const mongoose = require('mongoose');
const Config = require('./config');
let db = mongoose.createConnection('mongodb://127.0.0.1:27013,127.0.0.1:27012,127.0.0.1:27011/test', {
replicaSet: 'test',
readPreference: "secondaryPreferred"
},function(err){
if(err){
console.log('connect error.');
}else{
console.log('connect success.');
}
});
let UserModel = db.model('UserModel', new mongoose.Schema({
nick:String,
money:Number
}),'user');
async function test1(){
let doc = await UserModel.create([{nick:"a",money:10},{nick:"b",money:15}]);
}
async function test2(){
let session = await UserModel.startSession();
session.startTransaction();
try{
let opts = {session,new:true};
let a = await UserModel.findOneAndUpdate({nick:"a"},{$inc:{money:-2}},opts);
console.log(a.toObject());
let b = await UserModel.findOneAndUpdate({nick:"b"},{$inc:{money:2}},opts);
console.log(b.toObject());
await session.commitTransaction();
session.endSession();
}catch(err){
console.log(err);
await session.abortTransaction();
session.endSession();
}
console.log('transaction complete.');
}
test2();14 回复
https://github.com/e-oj/Fawn
@tsq 这个貌似是别人写的插件吧。
https://docs.mongodb.com/manual/core/transactions/index.html#transactions-and-sessions 文档里有呀兄弟
@aojiaotage 看到了,但还是不知道mongoose中怎么用。
我只看到issue里面说了要支持, 你在哪儿看到的支持了呀? mongo原生驱动是支持的… 可以用原生开个client,然后withSession… 不知道mongoose是怎么抽象的…好像没有暴露原生的client,
@lzszone 下面是mongoose的更新日志,其中有一条是支持mongodb4.0
既然都这样写了,我感觉mongoose应该是支持事务了,但没找到demo
mongoose也更新了么,太好了我去看看。
求分享一个demo出来~ 不过最新版应该还没这么快落地 还有时间可以观望一下
@lovegnep emmm… 加粗的那句话难道不是
吗? mongoose封装了mongodb啊…
@lzszone mogodb原生驱动我也没找到相关demo
来自酷炫的 CNodeMD
@lovegnep 使用这个方法 这样用…大概
@lzszone @koroshi @yokingma http://thecodebarbarian.com/a-node-js-perspective-on-mongodb-4-transactions.html 在mongoose官网上找到了demo
赞,4.0确实支持多文档事务了。。https://www.mongodb.com/transactions
MongoDB 4.0 adds support for multi-document ACID transactions, making it the only open source database to combine the speed, flexibility, and power of the document model with ACID guarantees. Through snapshot isolation, transactions provide a consistent view of data, and enforce all-or-nothing execution to maintain data integrity.
来自✨ Node.js开源项目精选✨
@lovegnep 感谢分享,很实用的例子,不过不过感觉不是新项目不太好升级呀- -我们生产的mongo还是3.2还是买的阿里云的任重道远呀