如何从猫鼬查询函数的回调中返回数据?

时间:2020-03-18 17:01:45

标签: node.js mongodb express mongoose mongoose-schema

这是我与mongodb合作的第一个项目,我正在使用expressmongoose开发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 };
        });
      });
    }
  });
}

Code on Github

问题出在功能shortenURL中。我正在尝试在JS objects块中返回if-else,但是它返回了URLSchema.findOne的结果。 如何从objects块返回if-else?请帮我!! 谢谢。

1 个答案:

答案 0 :(得分:0)

我只是从URLSchema.findOne({})中删除'return',因为您已经在函数内返回了json对象。为了进一步改善,我将以json形式返回错误,以简化错误处理。

const shortenURL = (url) => {
  if (!verifyURL(url)) {   //first check if the url is already shortened and stored
    console.log('INVALID URL!!!')
    return { error: "invalid URL" };
  }
  else {
    URLSchema.findOne({ url: url }, (err, storedURL) => { // removed return 
      if (err) {
          console.log('URLSchema.findOne() error:', err)
          return {error: err}; // returns error in json
      }
      if (storedURL) {
        //if URL is already shortened and stored
        console.log('StoredURL url', storedURL.url)
        console.log('StoredURL short', storedURL.short)
        return { original_url: storedURL.url, short_url: storedURL.short };
      }
      else {
        //if URL isn't already shortened and stored
        console.log('URL IS NOT SHORTEN AT ALLLLL!')
        incrementCounter((count) => {
          const newURL = new URLSchema({
            url: url,
            short: count
          });
          newURL.save((err) => {
            if (err) 
                console.log('newURL.save() error:', err)
                return {error: err}; // returns error in json
            }
            console.log('Returning og url', url)
            console.log('Returning count', count)
            return { original_url: url, short_url: count };
          });
        });
      }
    });
  }
}