簡體   English   中英

MongoDB:我似乎無法使用findOne查詢匹配項(使用mongoose,mLab)

[英]MongoDB: I can't seem to query matches with findOne (using mongoose,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;

完整的代碼在這里

您是否嘗試過使用.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'});
    });
});

暫無
暫無

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

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