簡體   English   中英

如何在Express JS中使用get方法從mongo db獲取數據?

[英]How to fetch data from mongo db using get method in express js?

我在mongo db中創建了兩個collection bear and bears。 我已經在快速代碼中定義了Bear集合,但是它正在訪問Bears數據。 我現在很困惑。 (熊和熊具有相同的字段(名字和名字),但值不同。

這是我的代碼

app.js

router.get('/api/bears', (req, res) => {
   console.log("dfgdg",req.body)
    Bear.getBears((err, bear) => {
        if(err){
            throw err;
        }
        console.log("fdggfd",bear);
        res.json(bear);
    });
});

型號/bear.js

const mongoose = require('mongoose');


const bearSchema = mongoose.Schema({
    first_name:{
        type: String,
        required: true
    },
    last_name:{
        type: String,
        required: true
    },
    create_date:{
        type: Date,
        default: Date.now
    }
});

const Bear = module.exports = mongoose.model('Bear', bearSchema);


module.exports.getBears = (callback, limit) => {
    Bear.find(callback).limit(limit);
}

誰能知道為什么提取熊數據而不是熊嗎?

您可以在mongoose.model使用第三個參數作為集合名稱,例如

//following will fetch the from bear collection
const Bear = module.exports = mongoose.model('Bear', bearSchema, 'bear');


//following will fetch the from bears collection
const Bear = module.exports = mongoose.model('Bear', bearSchema, 'bears');

從文檔

如果沒有傳遞任何集合參數,Mongoose將使用模型名稱。 如果您不喜歡這種行為,請傳遞一個集合名稱,使用mongoose.pluralize()或設置您的模式集合名稱選項。

參考 https://mongoosejs.com/docs/api.html#mongoose_Mongoose-model

我已經嘗試過您的代碼並且遇到了相同的問題,我通過向mongoose.model添加第三個參數來修復了該問題。模型指定了集合的名稱

const Bear = module.exports = mongoose.model('Bear', bearSchema, 'bear');

祝好運

暫無
暫無

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

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