【问题标题】:How to fix the "undefined" return from my mongoose/mongodb search function如何修复我的 mongoose/mongodb 搜索功能的“未定义”返回
【发布时间】:2019-05-28 13:12:46
【问题描述】:

我正在尝试从 mongodb 获取结果,然后将其传递给 const,但是得到“未定义”的返回值我哪里出错了?

我确保代码在没有返回的情况下工作并打印到控制台,并确保数据集存在于我的 mongodb 中。

const mongoose = require('mongoose');

function search(query) {
  const search = db.collection('spells').find({
    "name": query
  }).then(function(cursor) {
    cursor.forEach(function(spell) {
      console.log(spell);
      return spell;
    });
  });
}

mongoose.connect('mongodb://localhost/dnd', {
  useNewUrlParser: true
});

const db = mongoose.connection;

db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
  console.log("Connected to DB" + "\n");

});

console.log(search("Blight"));

当上面运行时,我在命令行上得到以下输出

未定义

连接到数据库

然后它打印以下是MongoDB中的数据

{ _id: 5ced1ce8aa89b60a7c2e34de,
  name: 'Blight',
  level: 4,
  school: 'N',
  time: [ { number: 1, unit: 'action' } ],
  range: { type: 'point', distance: { type: 'feet', amount: 30 } },
  components: { v: true, s: true },
  duration: [ { type: 'instant' } ],
  classes:
   { fromClassList: [ [Object], [Object], [Object], [Object] ],
     fromSubclass:
      [ [Object], [Object], [Object], [Object], [Object], [Object] ] },
  source: 'PHB',
  entries:
   [ 'Necromantic energy washes over a creature of your choice that you can see within range, draining moisture and vitality from it. The target must make a Constitution saving throw. The target takes {@dice 8d8} necrotic damage on a failed save, or half as much damage on a succ
essful one. This spell has no effect on undead or constructs.',
     'If you target a plant creature or a magical plant, it makes the saving throw with disadvantage, and the spell deals maximum damage to it.',
     'If you target a nonmagical plant that isn\'t a creature, such as a tree or shrub, it doesn\'t make a saving throw, it simply withers and dies.' ],
  entriesHigherLevel:
   [ { type: 'entries', name: 'At Higher Levels', entries: [Array] } ],
  page: 219,
  damageInflict: [ 'necrotic' ],
  savingThrow: [ 'constitution' ] }

我希望能够通过返回而不是在函数内部获取数据。

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    您当前正在将数据返回给 Promise,但您的函数没有返回任何内容,您可以返回数组对象并稍后处理结果

    async function search(query) {
      try {
        const search = await db.collection('spells').find({
          "name": query
        }).toArray();
        return search;
      } catch(err) {
        throw new Error(err);
      }
    }
    

    【讨论】:

      【解决方案2】:
      const mongoose = require('mongoose');
      
      function search(query) {
         return db.collection('spells').find({
          "name": query
        })
      }
      
      mongoose.connect('mongodb://localhost/dnd', {
        useNewUrlParser: true
      });
      
      const db = mongoose.connection;
      
      db.on('error', console.error.bind(console, 'connection error:'));
      db.once('open', function() {
        console.log("Connected to DB" + "\n");       
        search("Blight").then(console.log);
      });
      

      【讨论】:

        【解决方案3】:

        在 freenode/#Node.js 中从 avu 获得一些建议后,我研究了 Promise 并提出了这个问题。

        const mongoose = require('mongoose');
        
        function search(query) {
          return new Promise(function(resolve) {
              const findspell = db.collection('spells').find({
                "name": query
              }).then(function(cursor) {
                cursor.forEach(function(spell) {
                  resolve(spell)
                });
              });
            });
          }
        
          mongoose.connect('mongodb://localhost/dnd', {
            useNewUrlParser: true
          });
        
          const db = mongoose.connection;
        
          db.on('error', console.error.bind(console, 'connection error:'));
          db.once('open', function() {
            console.log("Connected to DB" + "\n");
        
          });
        
          search("Blight").then(console.log(response)});
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2019-07-12
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-09-03
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多