这可能是以前问过的,一个人如何从客户端连接到mongoDB / node.js服务器?对我来说,为了访问mongoDB数据库中的任何内容,我需要先登录:
client.connect(mongodb+srv://myusername:mypassword@cluster0-cvkxs.mongodb.net/test?retryWrites=true, {"useNewUrlParser":true}, (e, db) => {
//do mongoDB stuff and send things, and store db.db variable elsewhere, to send db.db("database").collection("something") to websocket clients when they verified / requested it...
}
问题是,为了从数据库中获取任何内容,我必须使用我的管理员用户来表示同意,如果对其进行了多个连接,则其他连接将自动注销。
因此,如果每次websocket客户端连接并希望从数据库获取数据,那么所有其他客户端将自动从数据库中注销(数据库对象被复制/传递给websocket客户端本身,例如在连接上,我这样做:每个客户端登录后ws.customDB = db。)
那么我该如何将客户端连接到数据库,以便多个人可以同时访问它(具有不同的特权)? 为了进一步说明,这是我完整的node.js代码:
var web = require("ws");
var wss = new web.Server({port:process.env.PORT || 8080});
var mongo = require("mongodb");
var client = mongo.MongoClient;
var url = "mongodb+srv://myusername:mypassword@cluster0-cvkxs.mongodb.net/test?retryWrites=true";
var DB = null;
var functionsToDo = {
"login":(ws, data) => {
console.log(data);
var u, p;
[[u, p] = [data["username"],data["password"]]];
if(u && p) {
tryToConnectToDB({"user":u,"pass":p}, (err, db) => {
var message = {
"loginCode":1
};
if(err) {
var errors = err["errors"];
if(errors) {
message["harsh errors"] = [];
for(var i = 0; i < errors.length; i++) {
if(errors[i]["err"]["code"] == 8000) {
message["loginCode"] = 0;
console.log("Wrong username or password!");
}
message["harsh errors"].push(errors[i]);
}
}
}
if(db) {
DB = db;
ws.myDB = db.db("cobysdata")
ws.mainDB = db;
ws.mainDB.on("close", () => {
ws.send(JSON.stringify(
{
"databaseStatus":"closed"
}
));
});
console.log("user " + data["username"] + " just logged on to this database:");
}
ws.send(JSON.stringify(message));
});
}
},
"get users":(ws, data) => {
functionsToDo["do database command"](ws, {wantResponse:"users",command:"find", collection:"people","query":{}});
},
"do database command":(ws, data) => {
tryToDoAction(ws, data, () => {
console.log("trying to do this with: " + data);
if(data["command"]) {
var c = data["command"];
var func = (e, r) => {
var msg = {};
if(e) {
console.log(e);
msg["harsh errors"] = "You got an error or something";
}
else {
msg[data["wantResponse"] || "your data"] = r;
msg["success"] = true;
try {
ws.send(JSON.stringify(msg));
console.log(JSON.stringify(msg));
} catch(e) {
ws.send(JSON.stringify({
message:"There was a success, but you could not display the results.",
success:true
}));
console.log(e, "bad msg?", msg);
}
}
};
var empt = {};
var curr = data["updateQuery"] || func;
var query = data["query"] || empt,
newvalues = data["new values"] || empt;
var col;
if(c != "createCollection")
col = ws.myDB.collection(data["collection"]);
else {
col = ws.myDB;
}
var commands = {
"find": {
"names": {
"find":["query"],
"toArray":["callback"]
}
},
"sort": {
"names": {
"find":[],
"sort":["query"],
"toArray":["callback"]
}
},
"limit": {
"names": {
"find":[],
"limit":["number"],
"toArray":["callback"]
}
},
"deleteOne": {
"args":["query","callback"]
},
"findOne": {
"args":["query", "callback"]
},
"insertOne": {
"args":["query", "callback"]
},
"insertMany": {
"args":["array"]
},
"remove": {
"args":["query", "callback"]
},
"drop": {
"args":["callback"]
},
"updateOne": {
"args":["query", "newvalues", "callback"]
},
"aggregate": {
"args": ["query"],
"hasCB":"toArray"
},
"createCollection": {
"args":["string", "callback"]
}
};
var otherDictionary = {
"query":query,
"callback":func,
"string":query,
"newvalues":newvalues,
"array":query,
"number":query
};
var val = commands[c];
var funcList, arguments;
if(val) {
funcList = [];
var n = val["names"];
if(n) {
for(var k in n) {
var functionName = k,
arguments = [];
n[k].forEach(x=>arguments.push(otherDictionary[x]));
funcList.push([functionName,arguments]);
}
}
else {
n = val["args"];
if(n) {
arguments = [];
n.forEach(x => {
arguments.push(otherDictionary[x]);
});
}
}
console.log("functions: ", JSON.stringify(funcList));
if(funcList.length > 0)
console.log(funcList.reduce((a, [key, args]) => a[key](...args), col));
else
console.log(console.log(col[c](...arguments)));
}
// col(query)["toArray"];
} else {
console.log("no command");
}
});
},
};
function tryToDoAction(ws, data, whatToDo) {
if(ws.myDB != null ) {
try {
whatToDo();
} catch(e) {
ws.send(JSON.stringify({
"medium error":e
}));
console.log(e);
}
} else {
ws.send(JSON.stringify({
"message":"Hey, you're not authorized to do that, log in first!!"
}));
console.log("Something happened");
}
}
function tryToConnectToDB(obj, cb) {
if(obj["user"] && obj["pass"]) {
var URL = `mongodb+srv://${obj["user"]}:${obj["pass"]}@cluster0-cvkxs.mongodb.net/test?retryWrites=true`;
client.connect(URL, {
reconnectTries: Number.MAX_VALUE,
reconnectInterval: 1000,
"useNewUrlParser":true
}, (err, db) => {
cb(err, db);
});
}
}
wss.on("connection", (ws) => {
ws.stillGoing = true;
var num = wss.clients.size;
console.log("clienfs",num);
var orig = {
"number of others":num
};
var ms = JSON.stringify(orig)
console.log("sending: ", ms, orig);
ws.send(ms);
ws.on("pong", () => ws.stillGoing = true);
console.log("Someone just connected!");
ws.on("message", (msg) => {
console.log("Checking this: ", msg, typeof msg);
var j = tryToParse(msg);
console.log("this is that tried to be parsed (or not): ", j);
for(var k in j) {
if(functionsToDo[k]) {
functionsToDo[k](ws, (j[k]));
}
}
});
ws.on("close", (ws) => {
console.log("Someone just left :(");
try {
ws.myDB = null;
DB.close();
} catch(e) {
}
});
});
var inter = setInterval(() => {
wss.clients.forEach(x => {
if(!x.stillGoing) {
x.terminate();
console.log("terminating the terminator");
}
x.stillGoing = false;
x.ping(() => {});
});
}, 10 * 1000);
function tryToParse(str) {
try {
return JSON.parse(str);
} catch(e) {
console.log(e);
return {};
}
}
function isJSON(string) {
try {
JSON.parse(string);
return true;
} catch(e) {
throw e;
return false;
}
}