GET request 'find by name' instead of find by id

Viewed 3292

Is there a way for me use this code or a similar code to find by username instead of findById?

Router.route('/:id').get(function (req, res)
 {
    let id = req.params.id;
    Books.findById(id, function (err, course) {
        res.json(course);
    });
});
2 Answers
Books.find({username: 'username'},function (err, course) {res.json(course);}); 

or

Books.find({username: /username/i},function (err, course) {res.json(course);}); // Like operator

I hope it works Look at Mongoose Docs here

There is no such thing called find by name. You can use find or findOne instead.

Books.find({username: 'username',function (err, course) {
    res.json(course);
});

Books.findOne({username: 'username',function (err, course) {
    res.json(course);
});

With Regex Pattern

Books.findOne({username: 'username'/gi,function (err, course) {
    res.json(course);
});
Related