MongoDB 无法在 js 函数中访问 StitchClient
MongoDB StitchClient cannot be accessed inside a js function
我已经在 "addUser()" 和 "loginUser()" 中调用了 stClient.login 函数,它们运行良好。我能够将用户添加到我的 MongoDB 数据库并在单击登录时找到用户。 (不要费心删除一个)在数据库中找到登录用户后,我正在加载一个新的 HTML 页面,我在其中传递登录用户的名称和从 MongoDB 检索到的个人资料照片。此外,我还想显示已登录用户的评论以及姓名和个人资料照片。问题来了:在 showComments 方法中,我无法访问 stitch 客户端。非常感谢任何帮助。
下面是代码:
Html 1:
<!DOCTYPE html>
<html>
<head>
<title>myFb</title>
<link rel="stylesheet" type="text/css" href="style1.css">
<script src="https://s3.amazonaws.com/stitch-sdks/js/library/v3/stable/stitch.min.js"></script>
<script src="assig02.js"></script>
</head>
<body onload="onLoadConnectDB()">
<p>Hello My App</p>
<div id="wlcom" align="center">
<button name="adding" onclick="addUser()">Add User</button><br>
<button name="deleting" onclick="deleteUser()">Delete User</button> <br>
<button name="logging" onclick="loginUser()">Login</button><br>
</div>
</body>
</html>
2 HTML秒的通用JS:
let db;
let itemsCollection;
let stClient;
let globalName;
let temp;
let clientPromise = stitch.StitchClientFactory.create('facebookclone-tlwvi');
function onLoadConnectDB(){
clientPromise.then(stitchClient=>{
stClient=stitchClient;
db = stClient.service('mongodb', 'mongodb-atlas').db('FbUsers');
itemsCollection=db.collection("ClonedFbUsers");
});
}
function addUser(){
var n= prompt("Your username: ")
const userId = stClient.authedId();
stClient.login().then(()=>
itemsCollection.insertOne({ owner_id: stClient.authedId(), userName : n , profilePhoto: "https://avatarfiles.alphacoders.com/115/115265.png", photos: ["NULL"],comments: [{msg:"NULL",time:"NULL",like:0}] })
).then(() => itemsCollection.find({}).execute())
.then(docs =>
docs.forEach((doc, index) =>
console.log(`${index}: ${JSON.stringify(doc)}`)
)
);
// });
alert("added");
}
function deleteUser(){
var d= prompt("Username to delete: ");
const userId = stClient.authedId();
stClient.login().then(()=>
itemsCollection.deleteOne({ userName: "Messi" })
).then(() => itemsCollection.find({}).execute())
.then(docs =>
docs.forEach((doc, index) =>
console.log(`${index}: ${JSON.stringify(doc)}`)
)
);
alert("User "+d+ " deleted.");
}
function loginUser(){
var n= prompt("Your username: ");
globalName=n;
const userId = stClient.authedId();
try{
stClient.login().then(()=>
itemsCollection.find({ userName : n }).execute()
).then(docs=>
loadUser(n,docs.map(c=>c.userName),docs.map(c=>c.profilePhoto)) //found result in db, send userName and pp link while loading a new user
);
}catch(err){
alert("not found a user");
}
// });
}
function loadUser(name,usName,pp){
if(usName!=""||usName!=null){
//sending name and profile photo link retrieved form db to 2nd HTML
document.location = "user.html?name="+encodeURIComponent(usName)+"&prof="+encodeURIComponent(pp);
//document.getElementById("name").value=name;
}else{
//no user in db
alert(name+ " is not found");
}
}
function onLoad () {
//onLoadConnectDB();
var pic;
var url = document.location.href,
params = url.split('?')[1].split('&'),
data = {}, tmp;
for (var i = 0, l = params.length; i < l; i++) {
tmp = params[i].split('=');
data[tmp[0]] = tmp[1];
}
document.getElementById('name').value = data.name;
document.getElementById('pp').src=decodeURIComponent(data.prof);
showComments(data.name);
// document.getElementById('pp').value=data.pp;
}
function showComments(globalName){
//ISSUE IS HERE!!
stClient.login().then(()=>
itemsCollection.find({ userName : globalName }).execute()
).then(docs=>
document.getElementById("comments").innerHTML = docs.map(c => "<div>" + c.comments + "</div>").join("")
);
};
HTML2
<!DOCTYPE html>
<html>
<head>
<title>MyProfile</title>
<link rel="stylesheet" type="text/css" href="style2.css">
<script src="https://s3.amazonaws.com/stitch-sdks/js/library/v3/stable/stitch.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
<script src="assig02.js"></script>
</head>
<header>
<div class="Header">
<div class="search">
<img src="white.png" >
</div>
<div class="profile curs">
<img src="me+.png">
<span class="barr" >     Home </span><span>                                    <img src="frndd.png">   <img src="messengerr.png"> <img src="notf.png" style="">         <img src="secret.png"></span>
</div>
</div>
</header>
<body onload="onLoad()">
<img id = "pp" src="" width="50" height="50">
<p> <input style="border: none; font-size: 20px; width: 100%" id="name" type="text" readonly></p>
<button type="submit" onclick="addPhoto()">Add Photo</button> <br>
<button type="submit">Choose Profile Photo</button><br>
<div class="comments" id="comments" onclick ="showComments()">
Show comments
</div>
</body>
</html>
问题与 async/sync 通信有关。在为 html2 分离 js 之后,假设连接已建立,我在 onLoad() 函数内部调用 onLoad2() 函数,但没有。应该 'wait' 直到建立连接,然后调用另一个函数。 js2:
let db;
let itemsCollection;
let stClient;
let globalName;
let temp;
let clientPromise = stitch.StitchClientFactory.create('facebookclone-tlwvi');
function onLoad(){
clientPromise.then(stitchClient=>{
stClient=stitchClient;
db = stClient.service('mongodb', 'mongodb-atlas').db('FbUsers');
itemsCollection=db.collection("ClonedFbUsers");
onLoad2(); //if you call outside then, wont work. onLoad2() will be interpreted before establishing connection to db
});
}
function onLoad2 () {
var pic;
var url = window.location.href,
params = url.split('?')[1].split('&'),
data = {}, tmp;
for (var i = 0, l = params.length; i < l; i++) {
tmp = params[i].split('=');
data[tmp[0]] = tmp[1];
}
document.getElementById('name').value = data.name;
document.getElementById('pp').src=decodeURIComponent(data.prof);
showComments(data.name);
}
function showComments(globalName){
console.log("i am here");
const userId = stClient.authedId();
stClient.login().then(()=>
itemsCollection.find({ userName : globalName }).execute()
).then(docs=>
document.getElementById("comments").innerHTML = docs.map(c => "<div>" + c.comments.msg + "</div>").join(" ")
);
}
function addComment(){
var n=document.getElementById("name").value;
var com= document.getElementById("comment").value
stClient.login().then(()=>
itemsCollection.updateOne({userName : n}, {$push:{comments:{msg:com,time:"22:30",like:4}}})
).then(() => itemsCollection.find({}).execute())
.then(docs =>
docs.forEach((doc, index) =>
console.log(`${index}: ${JSON.stringify(doc)}`)
)
);
}
HTML 对于 js2:
<!DOCTYPE html>
<html>
<head>
<title>MyProfile</title>
<link rel="stylesheet" type="text/css" href="style2.css">
<script src="https://s3.amazonaws.com/stitch-sdks/js/library/v3/stable/stitch.min.js"></script>
<script src="assig022.js"></script>
</head>
<header>
<div class="Header">
<div class="search">
<img src="white.png" >
</div>
<div class="profile curs">
<img src="me+.png">
<span class="barr" >     Home </span><span>                                    <img src="frndd.png">   <img src="messengerr.png"> <img src="notf.png" style="">         <img src="secret.png"></span>
</div>
</div>
</header>
<body onload="onLoad()">
<img id = "pp" src="" width="50" height="50">
<p> <input style="border: none; font-size: 20px; width: 100%" id="name" type="text" readonly></p>
<button type="submit" onclick="addPhoto()">Add Photo</button> <br>
<button type="submit">Choose Profile Photo</button><br>
<div class="comments" id="comments">
</div>
<br>
<input type="text" name="comment" id="comment" placeholder="Type comment">
<button onclick="addComment()">Send</button>
</body>
</html>
我已经在 "addUser()" 和 "loginUser()" 中调用了 stClient.login 函数,它们运行良好。我能够将用户添加到我的 MongoDB 数据库并在单击登录时找到用户。 (不要费心删除一个)在数据库中找到登录用户后,我正在加载一个新的 HTML 页面,我在其中传递登录用户的名称和从 MongoDB 检索到的个人资料照片。此外,我还想显示已登录用户的评论以及姓名和个人资料照片。问题来了:在 showComments 方法中,我无法访问 stitch 客户端。非常感谢任何帮助。 下面是代码:
Html 1:
<!DOCTYPE html>
<html>
<head>
<title>myFb</title>
<link rel="stylesheet" type="text/css" href="style1.css">
<script src="https://s3.amazonaws.com/stitch-sdks/js/library/v3/stable/stitch.min.js"></script>
<script src="assig02.js"></script>
</head>
<body onload="onLoadConnectDB()">
<p>Hello My App</p>
<div id="wlcom" align="center">
<button name="adding" onclick="addUser()">Add User</button><br>
<button name="deleting" onclick="deleteUser()">Delete User</button> <br>
<button name="logging" onclick="loginUser()">Login</button><br>
</div>
</body>
</html>
2 HTML秒的通用JS:
let db;
let itemsCollection;
let stClient;
let globalName;
let temp;
let clientPromise = stitch.StitchClientFactory.create('facebookclone-tlwvi');
function onLoadConnectDB(){
clientPromise.then(stitchClient=>{
stClient=stitchClient;
db = stClient.service('mongodb', 'mongodb-atlas').db('FbUsers');
itemsCollection=db.collection("ClonedFbUsers");
});
}
function addUser(){
var n= prompt("Your username: ")
const userId = stClient.authedId();
stClient.login().then(()=>
itemsCollection.insertOne({ owner_id: stClient.authedId(), userName : n , profilePhoto: "https://avatarfiles.alphacoders.com/115/115265.png", photos: ["NULL"],comments: [{msg:"NULL",time:"NULL",like:0}] })
).then(() => itemsCollection.find({}).execute())
.then(docs =>
docs.forEach((doc, index) =>
console.log(`${index}: ${JSON.stringify(doc)}`)
)
);
// });
alert("added");
}
function deleteUser(){
var d= prompt("Username to delete: ");
const userId = stClient.authedId();
stClient.login().then(()=>
itemsCollection.deleteOne({ userName: "Messi" })
).then(() => itemsCollection.find({}).execute())
.then(docs =>
docs.forEach((doc, index) =>
console.log(`${index}: ${JSON.stringify(doc)}`)
)
);
alert("User "+d+ " deleted.");
}
function loginUser(){
var n= prompt("Your username: ");
globalName=n;
const userId = stClient.authedId();
try{
stClient.login().then(()=>
itemsCollection.find({ userName : n }).execute()
).then(docs=>
loadUser(n,docs.map(c=>c.userName),docs.map(c=>c.profilePhoto)) //found result in db, send userName and pp link while loading a new user
);
}catch(err){
alert("not found a user");
}
// });
}
function loadUser(name,usName,pp){
if(usName!=""||usName!=null){
//sending name and profile photo link retrieved form db to 2nd HTML
document.location = "user.html?name="+encodeURIComponent(usName)+"&prof="+encodeURIComponent(pp);
//document.getElementById("name").value=name;
}else{
//no user in db
alert(name+ " is not found");
}
}
function onLoad () {
//onLoadConnectDB();
var pic;
var url = document.location.href,
params = url.split('?')[1].split('&'),
data = {}, tmp;
for (var i = 0, l = params.length; i < l; i++) {
tmp = params[i].split('=');
data[tmp[0]] = tmp[1];
}
document.getElementById('name').value = data.name;
document.getElementById('pp').src=decodeURIComponent(data.prof);
showComments(data.name);
// document.getElementById('pp').value=data.pp;
}
function showComments(globalName){
//ISSUE IS HERE!!
stClient.login().then(()=>
itemsCollection.find({ userName : globalName }).execute()
).then(docs=>
document.getElementById("comments").innerHTML = docs.map(c => "<div>" + c.comments + "</div>").join("")
);
};
HTML2
<!DOCTYPE html>
<html>
<head>
<title>MyProfile</title>
<link rel="stylesheet" type="text/css" href="style2.css">
<script src="https://s3.amazonaws.com/stitch-sdks/js/library/v3/stable/stitch.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
<script src="assig02.js"></script>
</head>
<header>
<div class="Header">
<div class="search">
<img src="white.png" >
</div>
<div class="profile curs">
<img src="me+.png">
<span class="barr" >     Home </span><span>                                    <img src="frndd.png">   <img src="messengerr.png"> <img src="notf.png" style="">         <img src="secret.png"></span>
</div>
</div>
</header>
<body onload="onLoad()">
<img id = "pp" src="" width="50" height="50">
<p> <input style="border: none; font-size: 20px; width: 100%" id="name" type="text" readonly></p>
<button type="submit" onclick="addPhoto()">Add Photo</button> <br>
<button type="submit">Choose Profile Photo</button><br>
<div class="comments" id="comments" onclick ="showComments()">
Show comments
</div>
</body>
</html>
问题与 async/sync 通信有关。在为 html2 分离 js 之后,假设连接已建立,我在 onLoad() 函数内部调用 onLoad2() 函数,但没有。应该 'wait' 直到建立连接,然后调用另一个函数。 js2:
let db;
let itemsCollection;
let stClient;
let globalName;
let temp;
let clientPromise = stitch.StitchClientFactory.create('facebookclone-tlwvi');
function onLoad(){
clientPromise.then(stitchClient=>{
stClient=stitchClient;
db = stClient.service('mongodb', 'mongodb-atlas').db('FbUsers');
itemsCollection=db.collection("ClonedFbUsers");
onLoad2(); //if you call outside then, wont work. onLoad2() will be interpreted before establishing connection to db
});
}
function onLoad2 () {
var pic;
var url = window.location.href,
params = url.split('?')[1].split('&'),
data = {}, tmp;
for (var i = 0, l = params.length; i < l; i++) {
tmp = params[i].split('=');
data[tmp[0]] = tmp[1];
}
document.getElementById('name').value = data.name;
document.getElementById('pp').src=decodeURIComponent(data.prof);
showComments(data.name);
}
function showComments(globalName){
console.log("i am here");
const userId = stClient.authedId();
stClient.login().then(()=>
itemsCollection.find({ userName : globalName }).execute()
).then(docs=>
document.getElementById("comments").innerHTML = docs.map(c => "<div>" + c.comments.msg + "</div>").join(" ")
);
}
function addComment(){
var n=document.getElementById("name").value;
var com= document.getElementById("comment").value
stClient.login().then(()=>
itemsCollection.updateOne({userName : n}, {$push:{comments:{msg:com,time:"22:30",like:4}}})
).then(() => itemsCollection.find({}).execute())
.then(docs =>
docs.forEach((doc, index) =>
console.log(`${index}: ${JSON.stringify(doc)}`)
)
);
}
HTML 对于 js2:
<!DOCTYPE html>
<html>
<head>
<title>MyProfile</title>
<link rel="stylesheet" type="text/css" href="style2.css">
<script src="https://s3.amazonaws.com/stitch-sdks/js/library/v3/stable/stitch.min.js"></script>
<script src="assig022.js"></script>
</head>
<header>
<div class="Header">
<div class="search">
<img src="white.png" >
</div>
<div class="profile curs">
<img src="me+.png">
<span class="barr" >     Home </span><span>                                    <img src="frndd.png">   <img src="messengerr.png"> <img src="notf.png" style="">         <img src="secret.png"></span>
</div>
</div>
</header>
<body onload="onLoad()">
<img id = "pp" src="" width="50" height="50">
<p> <input style="border: none; font-size: 20px; width: 100%" id="name" type="text" readonly></p>
<button type="submit" onclick="addPhoto()">Add Photo</button> <br>
<button type="submit">Choose Profile Photo</button><br>
<div class="comments" id="comments">
</div>
<br>
<input type="text" name="comment" id="comment" placeholder="Type comment">
<button onclick="addComment()">Send</button>
</body>
</html>