MongoDB:我似乎无法查询与findOne的匹配(使用mongoose,mLab)

时间:2017-05-03 11:13:29

标签: node.js mongodb mlab

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
  });
}

我正在使用koa.js。即使有匹配也似乎不匹配。

我用mongoose.connect连接到mLab

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

1 个答案:

答案 0 :(得分:0)

您是否尝试过使用.find()代替.findOne()?我也完成了这个项目,虽然我使用了promises(你可以设置mongoose来全局使用它们):

//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'});
    });
});