Reputation: 5924
I'm running into an issue where I am able to access the records associated with my mongoose model object, but I cannot access the properties of the records using dot notation. For some reason I can get the record, but when I try to use dot notation to grab that records specific property, I get undefined
.
Here is my model:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var imageSchema = new Schema({
pattern: { type: String, enum: ['solid', 'stripe', 'plaid'] },
color: { type: String, enum: ['grey', 'navy-blue', 'black', 'khaki', 'brown'] },
imageName: String,
imageUrl: String,
imageSource: String
});
var Images = mongoose.model('Images', imageSchema);
module.exports = Images;
Here is my route being defined:
router.get('/:pattern/:color/result', function(req, res){
console.log(req.params.color);
Images.find( { pattern: req.params.pattern, color: req.params.color }, function(err, image){
if (err) { console.log(err); }
console.log(image);
console.log(image.pattern);
res.render('pages/result.hbs', {
pattern : req.params.pattern,
color : req.params.color,
image : image
});
});
});
The console.log(image) retrieves records like:
[ { _id: 55e35b3b9bd509dbc0b46c79,
pattern: 'solid',
color: 'navy-blue',
imageName: 'blueshirtesrsasdfff.jpg',
imageUrl: 'https://imageurl.com',
imageSource: 'source.com' } ]
The console.log(image.pattern) retrieves this response:
undefined
Where am I making a mistake and calling a specific property?
Upvotes: 0
Views: 169
Reputation: 8523
.find
returns an array of elements (you can tell by the square brackets surrounding the image object in your console.log). If you want to keep your query the same, you'll actually need to use image[0].pattern
.
Alternatively, you can use Images.findOne
, like so
Images.findOne( { pattern: req.params.pattern, color: req.params.color }, function(err, image){
if (err) { console.log(err); }
...
});
Upvotes: 3