2017-05-03 71 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