在我的Node JS / Express中,我试图使用以下代码查询ID:
router.get('/module/:id/', (req, res ) => {
try {
console.log('in get module')
const luamodule = LuaModule.findById('5eb2818c955bc7202498cd09')
console.log('module name is ' + luamodule.name)
} catch (error) {
console.log('In error --> ' + error)
res.status(404).send(error.Message)
}
})
尽管记录存在ID-5eb2818c955bc7202498cd09,该函数不会返回记录。
console.log输出“模块名称未定义”作为输出。
在models目录中遵循luamodule.js
const validator = require('validator')
const luaModuleSchema = new mongoose.Schema({
name: {
type: String,
required: true,
trim: true
},
email: {
type: String,
// unique: true,
required: true,
trim: true,
lowercase: true,
validate(value) {
if (!validator.isEmail(value)) {
throw new Error('Email is invalid')
}
}
},
environment: {
type: String,
required: true,
trim: true,
},
description: {
type: String,
required: true,
trim: true,
},
modulefile: {
type: Buffer
},
})
const luaModule = mongoose.model('LuaModule', luaModuleSchema)
module.exports = luaModule ```
End objective of the exercise is to accept the parameters from client and return the zip file stored into database.
Appreciate any help in this regard.
答案 0 :(得分:1)
node.js是异步的,此LuaModule.findById('5eb2818c955bc7202498cd09')
代码返回Promise
对象。
您必须履行这一诺言才能取得结果,请尝试这种方式
router.get('/module/:id/', async (req, res ) => {
try {
console.log('in get module')
const luamodule = await LuaModule.findById('5eb2818c955bc7202498cd09')
console.log('module name is ' + luamodule.name)
} catch (error) {
console.log('In error --> ' + error)
res.status(404).send(error.Message)
}
})
答案 1 :(得分:0)
您可以遵循此代码
型号
const validator = require('validator')
const luaModuleSchema = new mongoose.Schema({
name: {
type: String,
required: true,
trim: true
},
email: {
type: String,
// unique: true,
required: true,
trim: true,
lowercase: true,
validate(value) {
if (!validator.isEmail(value)) {
throw new Error('Email is invalid')
}
}
},
environment: {
type: String,
required: true,
trim: true,
},
description: {
type: String,
required: true,
trim: true,
},
modulefile: {
type: Buffer
},
})
const LuaModule = mongoose.model('LuaModule', luaModuleSchema)
module.exports = LuaModule
> Controller
router.get('/module/:id/', async (req, res ) => {
try {
console.log('in get module')
const luamodule =await LuaModule.findById('5eb2818c955bc7202498cd09')
console.log('module name is ' + luamodule.name)
} catch (error) {
console.log('In error --> ' + error)
res.status(404).send(error.Message)
}
})