【问题标题】:Why return not works in Mongoose findOne method?为什么 return 在 Mongoose findOne 方法中不起作用?
【发布时间】:2016-10-26 17:08:23
【问题描述】:

我尝试按名称查找一项,然后更新表并返回更新后的结果,但返回不起作用。我的代码:

class addSongsToArtist {

    constructor(artistName) {

        Artist.findOne({
            name: artistName
        }).exec((err, data) => {
            if (err) console.log(err);

            data.name = 'updated name'
            data.save();

            return data // * not work 
        });
    }
}

进入 exec 方法,我看到了正确结果的数据,并保存了 mongo 控制台结果。但返回不起作用。我尝试将更改保存到外部变量并在 Promise 中返回结果,但它也不起作用。 为什么它不起作用?

【问题讨论】:

  • not work 是什么意思?它是一种异步方法,那么您如何尝试接收data 的值来使用它?你能分享那段代码吗?
  • data.save 是 i/o,所以需要时间。在 Mongoose 玩它之前,您什么都不会归还。试试data.save(function(err){return data})
  • 你需要了解 js 中的异步行为。看看stackoverflow.com/questions/14220321/…

标签: javascript node.js mongoose


【解决方案1】:

你使用 .save 异步函数作为同步函数,试试这个:

constructor(artistName) {

    Artist.findOne({
        name: artistName
    }).exec((err, data) => {
        if (err || !data){
           console.log(err);
           return null;
        }
        else
        {
          data.name = 'updated name'
          data.save(function(err, savedDatas)
          {
             if(err || !savedDatas)
             {
                return null;
             }
             else
             {
                return savedDatas; // * not work 
             }
          });
        }
       });

【讨论】:

    【解决方案2】:

    我有解决办法。返回新对象实例的构造方法存在问题。 工作代码:

    class addSongsToArtist {
        constructor(artistName) {
          this.result = false
            Artist.findOne({
                name: artistName
            }).exec((err, data) => {
                if (err) console.log(err);
    
                data.name = 'updated name'
                data.save();
                this.result = data
            });
        }
    
      /**
      * need call in promise after call new addSongsToArtist()
      */
      getData() {
        return this.result
      }
    }
    

    并获取数据:

    let findOne;
    Promise.resolve()
      .then(()=>{
         findOne = new addSongsToArtist()
       })
      .then(()=>{
         findOne.getData()
       });
    

    【讨论】:

      猜你喜欢
      • 2015-02-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-15
      • 2023-03-03
      • 2018-03-21
      • 2021-02-11
      • 2012-03-26
      相关资源
      最近更新 更多