无法在js函数内访问MongoDB StitchClient

时间:2018-04-15 10:02:53

标签: javascript html mongodb mongodb-atlas mongodb-stitch

我已经调用了stClient.login函数" addUser()"和" loginUser()"他们工作得很好。我可以将用户添加到我的MongoDB数据库,并在登录时查找用户。 (不要打扰删除一个)在DB中找到一个已登录的用户后,我正在加载一个新的HTML页面,我在其中传递从MongoDB检索到的已登录用户和profil照片的名称。此外,我还想显示已登录用户的评论以及姓名和个人资料照片。问题出现了:在showComments方法中,我无法访问stitch客户端。任何帮助都非常感谢。 以下是代码:

Html 1:

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("")
        );
        };

2个HTML的常见JS:

<!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" >     &nbsp &nbsp Home </span><span> &nbsp &nbsp &nbsp&nbsp &nbsp &nbsp&nbsp &nbsp &nbsp&nbsp &nbsp &nbsp &nbsp &nbsp &nbsp&nbsp &nbsp &nbsp&nbsp&nbsp &nbsp<img src="frndd.png"> &nbsp <img src="messengerr.png"> <img src="notf.png" style=""> &nbsp &nbsp &nbsp &nbsp <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>

HTML2

{{1}}

1 个答案:

答案 0 :(得分:0)

该问题与异步/同步通信有关。在为html2分离js之后,我在假设连接建立之后调用onLoad()函数中的onLoad2()函数,但是没有。应该'等待'直到建立连接然后再调用另一个函数。 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)}`)
        )
      );

   }

js2的HTML:

    <!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" >     &nbsp &nbsp Home </span><span> &nbsp &nbsp &nbsp&nbsp &nbsp &nbsp&nbsp &nbsp &nbsp&nbsp &nbsp &nbsp &nbsp &nbsp &nbsp&nbsp &nbsp &nbsp&nbsp&nbsp &nbsp<img src="frndd.png"> &nbsp <img src="messengerr.png"> <img src="notf.png" style=""> &nbsp &nbsp &nbsp &nbsp <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>