-2
私はNode.jsとMongoDBでshortenUrl APIを書いています。nodejで2つのmongodbクエリを同期して操作するにはどうすればよいですか?
私は、増分IDを格納するコレクションを使用しています。
サーバは、最新の利用可能numberIDためdatabase
、
を聞いてきます
- ユーザーが短縮URLを要求するたびに、そして、base62変換を行います。
しかし、Nodejsの非同期機能のために、増分IDを取得して新しいURLペアを挿入する終了時刻はわかりません。時々、サーバはIDをインクリメントせずにURLペアを挿入します。
app.post("/" , function(req , res) { const curLongUrl = req.body.longUrl; const data = { longUrl : curLongUrl, shortUrl : "" }; const IDurl = "https://shortenurl-rustyblade.c9users.io/"; mongo.connect(url , function(err , db) { if(err) { return console.log(err); } const increment = db.collection("autoIncrement"); increment.findOne({"function" : "incrementKey"} , function(err , docs) { if(err) { return console.log(err); } const curID = docs.increment; console.log(curID); const curShortUrl = IDurl + curID; data.shortUrl = curShortUrl; db.close(); }); }); mongo.connect(url , function(err , db) { if(err) { return console.log(err); } const col = db.collection("urlTable"); col.insert(data , function(err , document) { if(err) { return console.log(err); } console.log(JSON.stringify(data)); db.close(); res.send(JSON.stringify(data)); }); }); //res.send(JSON.stringify(data)); });
ノードの非同期性のためにドキュメントを読んで検索してください。このタイプの質問には、.check asyncメソッドと約束が必要です。私は開始をコーディングする前にこれを最初に見ています。 –