koque
koque

Reputation: 2256

Mongodb: findById() returns no value

The following findById() returns null even though the id exists in the database:

router.get('/product/:id', function (req, res) {

console.log("product id = " + req.params.id);

//produces product id = 596161e1734d1d25634366ce

var id = req.params.id;

Product.findById({_id: req.params.id})
    .exec(function (err, product) {
        if (err) {
            console.error('Error retrieving all product by id!');
        } else {
            console.log('server product = ' + JSON.stringify(product));
            res.json(product);
        }
    })
})

Target document in database:

{
    "_id": {
        "$oid": "596161e1734d1d25634366ce"
    },
    "producttype": "stove",
    "name": "30 in. 4.8 cu. ft. Electric Range in Stainless Steel",
    "brand": "Amana",
    "model": "AER6303MFS",
}

Model:

const mongoose = require('mongoose');

const Schema = mongoose.Schema;

const ProductSchema = new Schema({
    _id: String,
    productType: String,
    name: String,
    brand: String,
    model: String,
    price: Number,
    discount: Number,
    description: String,
    rating: Number,
    sku: String,
    warranty: String,
});

var Product = mongoose.model('Product', ProductSchema, 'product');
module.exports=Product;                  

Upvotes: 2

Views: 3875

Answers (2)

sohamdodia
sohamdodia

Reputation: 377

Try to remove _id from your ProductSchema. Id will be automatically generated by the mongodb. After that try using

Product.find({_id: req.params.id})
    .exec(function (err, product) {
        if (err) {
            console.error('Error retrieving all product by id!');
        } else {
            console.log('server product = ' + JSON.stringify(product));
            res.json(product);
        }
    })
})

or if you want to use find by id then use

Product.findById(req.params.id)
    .exec(function (err, product) {
        if (err) {
            console.error('Error retrieving all product by id!');
        } else {
            console.log('server product = ' + JSON.stringify(product));
            res.json(product);
        }
    })
})

Upvotes: 2

Andy Aldo
Andy Aldo

Reputation: 890

Taken from the docs, have you tried passing just the req.params.id instead of an object? like so:

Product.findById(req.params.id)
    .exec(function (err, product) {
        if (err) {
            console.error('Error retrieving all product by id!');
        } else {
            console.log('server product = ' + JSON.stringify(product));
            res.json(product);
        }
    })
})

Upvotes: 1

Related Questions