/ Published in: JavaScript
MongoDB
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
makeId = function (doc) { var id = Math.floor(Math.random() * 900000) + 100000, that = this; // max(900000)/min(100000) var key = "", i, v, that = this; for (i = 0; i < 32; i++) { v = Math.random() * 16 | 0; if (i == 8 || i == 12 || i == 16 || i == 20) { key += '-'; } if (i == 12) { key += '4'; } else { key += (i == 16 ? (v & 3 | 8) : v).toString(16); } } var res = db.users.findOne({$or: [ {id: id}, {key: key} ]}); if(res) { makeId(doc); } else { doc.id = id; doc.key = key; db.users.save(doc); print(id); } } db.users.ensureIndex({id:1},{unique:true,sparse:true}) db.users.ensureIndex({key:1},{unique:true,sparse:true}) db.users.find().limit(10).forEach(function(doc){ makeId(doc); }) db.friends.find().limit(100000).forEach(function (doc) { var user = db.users.findOne({mysql_id: doc.user2}); var friend = db.users.findOne({mysql_id: doc.user1}); if (user && friend) { if (!(db.users.findOne({mysql_id: doc.user2, followers: friend._id}))) { user.followers.push(friend._id); db.users.save(user); print(friend._id); } } });