如何修复我的猫鼬/ mongodb搜索功能的“未定义”返回值

时间:2019-05-28 13:12:47

标签: node.js mongodb mongoose

我正在尝试从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' ] }

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

3 个答案:

答案 0 :(得分:0)

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);
});

答案 1 :(得分:0)

您当前正在将数据返回给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 :(得分:0)

在freenode /#Node.js中从avu获得一些建议后,我研究了promises并提出了这种选择。

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)});