I'm trying to import img url from my database (mongodb) using mongoose, and display it with EJS, my problem is that I always get undefined.
The data I get when using findById is "item" =
[
{
_id: 5b809b2c74e2f54c20ae30da,
brand: 'honda',
model: 'cbr250r',
price: 20000,
amount: 20,
img: 'https://news.maxabout.com/wp-content/uploads/2016/12/22.png',
backImg: 'https://wallpapercave.com/wp/wp3065342.png',
views: 1,
desc: 'this is a bike description'
}
]
and I'm trying getting my "backImg" using this path: "item[0].backImg". When I console.log it I get undefined. I also tried "item.backImg"
that's the route file which includes the function:
const router = require('express').Router();
const bodyParser=require('body-parser')
const urlencodedParser =bodyParser.urlencoded({extended:false})
router.use(bodyParser.json());
router.use(bodyParser.urlencoded({ extended: true }));
const itemModel = require('../models/itemsModel')
const userModel = require('../models/userModel')
//items//
router.get('/:_id',(req,res)=>{
console.log(req.params._id)
let q = itemModel.find({_id:req.params._id})
q.exec(function(err,item){
if(err){
console.log(err)
} else {
console.log(item)
console.log(item[0].brand)
console.log(item[0].backImg)
console.log(item.backImg)
res.render('./pages/items' , {item:item,user: req.user,} )
}
})
})
module.exports = router
I think it should be like this
..... // previous code
itemModel.findOne({_id:req.params._id})
.then((item)=>{
if(!item){
console.log("No record found");
}
console.log(item)
console.log(item.brand)
console.log(item.backImg)
})
.catch(err=>{
console.log("Error",err)
})
Here you can see I have used the findOne method of mongoose that will give only 1 result (single object) from database.Also check if req.params._id
is not undefined
.If you have any queries let me know.
所以它似乎那些作为 undefiend 导入的字段没有添加到项目架构中,所以这就是问题所在
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.