【发布时间】:2020-06-29 19:44:39
【问题描述】:
这是我第一个使用 mongodb 的项目,我正在使用 express 和 mongoose 开发一个 URL 缩短器。我在从回调函数返回数据时遇到问题。
我有两个架构如下:
//Store the url, corresponding short url and number of clicks.
const urlSchema = new Schema({
url: {
type: String,
required: true
},
short: {
type: Number,
require: true,
unique: true
},
clicks: {
type: Number,
required: true,
default: 0
}
});
//Stores the number of documents in URL Schema.
const urlCounter = new Schema({
count: {
type: Number,
default: 1
}
});
以及保存文档的处理函数
//Count and increment the number of documents in URLSchema
const incrementCounter = (callback) => {
URLCounter.findOneAndUpdate({}, { $inc: {count: 1 } }, (err, counter) => {
if (err) return console.error(err);
if (counter) {
callback(counter.count);
}
else {
const newCounter = new URLCounter();
newCounter.save((err, counter) => {
if (err) return console.error(err);
URLCounter.findOneAndUpdate({}, { $inc: {count: 1 } }, (err, counter) => {
if (err) return console.error(err);
callback(counter.count);
});
});
}
});
}
const shortenURL = (url) => {
if (!verifyURL(url)) {
return {error: "invalid URL"};
}
//first check if the url is already shortened and stored
return URLSchema.findOne({url: url}, (err, storedURL) => {
if (err) return console.error(err);
if (storedURL) {
//if URL is already shortened and stored
return { original_url: storedURL.url, short_url: storedURL.short };
}
else {
//if URL isn't already shortened and stored
incrementCounter((count) => {
const newURL = new URLSchema({
url: url,
short: count
});
newURL.save((err) => {
if (err) return console.error(err);
return { original_url: url, short_url: count };
});
});
}
});
}
问题在于函数shortenURL。我试图在if-else 块内返回JS objects,但它返回URLSchema.findOne 的结果。
如何从if-else 块返回objects?请帮我!!
谢谢你。
【问题讨论】:
标签: node.js mongodb express mongoose mongoose-schema