簡體   English   中英

嘗試使用Javascript查詢MongoDB,返回空

[英]Trying to query MongoDB with Javascript, returns empty

這總是返回一個空數組。

<!--
tid - int64
ts - timestamp
url - string
topic - string
msg - string
-->

<script src="https://s3.amazonaws.com/stitch-sdks/js/bundles/4.3.1/stitch.js"></script>
<script>
    const client = stitch.Stitch.initializeDefaultAppClient("twebh-rufmj");

    const db = client
        .getServiceClient(stitch.RemoteMongoClient.factory, "mongodb-atlas")
        .db("forums");

    client.auth
        .loginWithCredential(new stitch.AnonymousCredential())
        .catch(err => {
            console.error(err);
        })
        .then(displayEmployees);

    function displayEmployees() {
        db.collection("posts")
            .find({}, { limit: 1000 })
            .toArray()
            .then(docs => {
                const html = docs.map(doc => `<div>${doc.topic}</div>`);
                document.getElementById("comments").innerHTML = html;
            });
    }
</script>

<div id="comments"></div>

我希望返回的主題是“測試”,因為這就是我在數據庫中記錄的內容。 我嘗試了來自MongoDB Wiki的許多不同示例代碼,但這在Chrome的控制台中未返回任何錯誤,但我沒有得到返回的值。

我認為您沒有從db query獲得任何價值的原因是因為您的find查詢存在輕微問題。

您正在傳遞limit :1000作為find查詢的第二個參數,但它應該是第三個參數。 第二個參數應該是projection ,第三個參數是query options (通過限制)

您需要傳遞空對象作為第二個參數,並傳遞{limit:1000}作為第三個參數。

另外,最好在map之后執行.join() ,以便它向innerHTML返回字符串而不是數組。

嘗試這個 :

function displayEmployees() {
    db.collection("posts")
        .find({}, {}, { limit: 1000 })
        .toArray()
        .then(docs => {
            const html = docs.map(doc => `<div>${doc.topic}</div>`).join('');
            document.getElementById("comments").innerHTML = html;
        });
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM