Node.js MongoDB:我能';似乎无法查询与findOne的匹配(使用mongoose、mLab) 我用KOA.JS做这个。即使有匹配,它似乎也不匹配
我用猫鼬连接到mLabNode.js MongoDB:我能';似乎无法查询与findOne的匹配(使用mongoose、mLab) 我用KOA.JS做这个。即使有匹配,它似乎也不匹配,node.js,mongodb,mlab,Node.js,Mongodb,Mlab,我用猫鼬连接到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
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
});
}
这是我的模式:
const url = require('./models/url'); //require model
完整的代码是。您是否尝试过使用
.find()
而不是.findOne()
?我也做过这个项目,尽管我使用了承诺(您可以设置mongoose在全球范围内使用它们):
findOne
返回什么?有什么错误吗?如果没有找到匹配项,则返回我设置的错误。我知道事实上确实存在匹配项。您是在查询现有集合吗?如果是,该集合的名称是什么?Mongoose将使用您显示的代码查询名为URL
(复数)的集合。是的,我正在查询现有集合。可以找到完整的代码。我在模式中设置的集合的名称在mLab中是“url”,其复数形式称为url
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;
//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'});
});
});