【问题标题】:How to return data from callback of mongoose query function?如何从猫鼬查询函数的回调中返回数据?
【发布时间】:2020-06-29 19:44:39
【问题描述】:

这是我第一个使用 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。我试图在if-else 块内返回JS objects,但它返回URLSchema.findOne 的结果。 如何从if-else 块返回objects?请帮我!! 谢谢你。

【问题讨论】:

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


    【解决方案1】:

    我只想从 URLSchema.findOne({}) 中删除“返回”,因为您已经在函数内返回了 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 };
              });
            });
          }
        });
      }
    }
    

    【讨论】:

    • 嗯,我想知道你这次回来的是什么?我想知道回调函数内部发生了什么,所以我更新了我的答案。你能运行它并告诉我打印了什么吗?
    猜你喜欢
    • 2018-05-26
    • 1970-01-01
    • 2019-09-29
    • 2022-11-22
    • 2018-03-07
    • 1970-01-01
    • 2016-05-22
    • 1970-01-01
    • 2020-07-19
    相关资源
    最近更新 更多