【发布时间】: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' ] }
我希望能够通过返回而不是在函数内部获取数据。
【问题讨论】: