2017-05-03 31 views
0
async function red(ctx) { 
    let redurl = "//url here"; 
    url.findOne({ shortenedLink: redurl }, (err, data) => { 
    //find if short url matches long url in db 
    if (err) throw err; 
    if (data) { 
     //if matches then redirect to long url 
     ctx.redirect(data.url); 
     console.log("matched"); 
    } else console.error("--"); //getting this error, it doesn't find any matches even though there are 
    }); 
} 

Im使用koa.js爲此。即使有匹配它似乎不匹配。MongoDB:我似乎無法查詢匹配與findOne(使用貓鼬,mLab)

我連接到MLAB與mongoose.connect

const url = require('./models/url'); //require model 

這是我的架構:

const mongoose = require('mongoose'); 
const Schema = mongoose.Schema; 

const urlSchema = new Schema({ 
    url: String, 
    shortenedLink: String 
},{timestamps: true}); 

const url = mongoose.model('url',urlSchema); 
module.exports = url; 

完整的代碼是here

+0

'findOne'返回什麼?任何錯誤或什麼? –

+0

如果發現不匹配,則返回該錯誤。我知道有一個事實,即實際上有匹配。 – furball514

+0

您是否正在查詢現有集合?如果是這樣,那個集合的名稱是什麼? Mongoose會用你正在顯示的代碼查詢一個名爲'urls'(複數)的集合。 – robertklep

回答

0

您是否嘗試過使用.find()而不是.findOne()?我也完成了這個項目,儘管我使用了諾言(你可以設置貓鼬在全球範圍內使用它們):

//search for shortened URL ID in database, then redirect user if shortened URL ID is found 
//if not found, send JSON response with error 

app.get('/:id', (req, res) => { 
    Urls.find({ 
     shortlink: req.params.id 
    }).then((url) => { 
     let redirecturl = url[0].url; 
     res.redirect(redirecturl); 
    }).catch((e) => { 
     res.status(404).send({error: 'Shortened URL ID not found'}); 
    }); 
}); 
+0

still不工作 – furball514