簡體   English   中英

無法將MongoDB中的JSON數據轉換為可在我的代碼中使用的變量

[英]can't convert JSON data from MongoDB to variable usable in my code

需要從我的MongoDB中提取數據並使用expressJS和mongoose在我的Web應用程序中用作變量。 當我使用find()函數請求所有數據時,我將此數據作為JSON獲取,沒有任何問題。 但是現在我需要能夠訪問集合,因為它將數據用作我項目中的變量。 請幫助我,我知道我錯過了什么。

router.get('/support', (req, res) => {

Message.find()
.then(messages => {
    res.json({
        confirmation: 'success',
        data: messages
    })
})
.catch(err => {
    res.json({
        confirmation: 'fail',
        message: err.message
    })
})
});

可能是因為你有

Message.find()

代替

Message.find({})

嘗試這個:

router.get('/support', (req, res) => {

Message.find({}).exec()
.then(messages => {
    res.json({
        confirmation: 'success',
        data: messages
    })
})
.catch(err => {
    res.json({
        confirmation: 'fail',
        message: err.message
    })
})
});

第一件事:添加{}作為查詢條件。 也許mongoose會接受空參數,但我不確定它是如何處理的(我沒有在文檔中看到有關這種語法的任何提及)。

第二: findOne不返回承諾。 查詢結果有一個方便then方法,但我不確定catch 你應該執行exec()來獲得一個js的承諾。

查詢不是承諾

Marcin的評論會很好,或者如果你不需要你視圖中的所有項目,你只能發送:

 res.json({
    confirmation: 'success',
    message: messages.body,
    sender: messages.sender
 })

在收到來自此類用戶的一些指示后,我設法讓它工作。 我不知道它是否是正確的方法,但我的代碼工作方式如此,所以我決定更新對我有用的東西。 我將中間件更新為此

router.get('/support', (req, res) => {
    Message.find({})
    .then(messages => {
        res.render("support", {messages}); // I rendered the template 
})
    .catch(err => {
        res.json({
            confirmation: 'fail',
            message: err.message
        })
    })   
});

然后在我的EJS文件中我簡單地添加了它

<p><%= messages[0].sender %></p>

這對我有用

暫無
暫無

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

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