2017-05-03 3 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(mongoose、mLabを使用)との照合ができないようです。

私はmongoose.connect

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

とMLABに接続これは私のスキーマです:

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

.findOne()の代わりに.find()を試しましたか?私はこのプロジェクトも行っていますが、私は約束を使っていますが(グローバルに使用するようにマングースを設定することもできます):

//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

動作していない – furball514

関連する問題