Giter VIP home page Giter VIP logo

Comments (3)

pbatey avatar pbatey commented on July 20, 2024 1

query-to-mongo doesn't support ObjectId comparisons. I think you should have a separate route for accessing an object by it's id.

For example for a 'users' collection, you'd have the /api/v1/users route for queries and /api/v1/user/:id for accessing a single user.

https://localhost/api/v1/users?firstName=John would find users with a firstName of 'John', but https://localhost/api/v1/user/5a4de6a93eecc8aeb8882f76 would return the user document with the id matching ObjectId("5a4de6a93eecc8aeb8882f76")

Basically, you don't have to use query-to-mongo if you already know the id.

You could implement a {{base_url}}/api/formdata/my/:id route like this:

var express = require('express')
var mongoskin = require('mongoskin')
var ObjectID = require('mongodb').ObjectID
var query2m = require('query-to-mongo')

// attach db to the router
var db = mongoskin.db('mongodb://localhost:27017/mydb', {safe: true})
var router = express.Router()
router.db = db
router.use(function (req, res, next) {
    req.db = router.db
    next()
})

// get an object from the collection
router.get('/my/:id', function (req, res, next) {
    var collection = req.db.collection('my')
    collection.findOne(new ObjectId(req.idMatch), function (e, result) {
        if (e) return next(e)
        if (!result) res.status(404) // Not Found
        res.locals.json = result
        next()
    })
})

// query objects in the collection
router.get('/my/query', function (req, res, next) {
    var query = query2m(req.query, { ignore: 'envelope' })
    var collection = req.db.collection('my')

    collection.count(query.criteria, function (e, count) {
        var links
        if (e) return next(e)
        res.append('X-Total-Count', count)
        var fullUrl = req.protocol + '://' + req.get('host') + req.originalUrl
        links = query.links(fullUrl, count)
        if (links) res.links(links)
        req.collection.find(query.criteria, query.options).toArray(function (e, results) {
            if (e) return next(e)
            res.locals.json = results
            next()
        })
    })
})

// attach the route to the app and serve
var app = express()
app.use('/api/formdata', router)
var server = app.listen(3000, function () {
    console.log('Listening on Port', server.address().port)
})

For more of insight into my thinking on REST APIs you can see the express-mongo-rest project here.

from query-to-mongo.

sharathchandramg avatar sharathchandramg commented on July 20, 2024

Agreed, However when we are looking @ Microservices it might be useful to have a general query pattern

Below is a sample of what I am thinking of implementing.

router.get("/query", asyncMiddleware(async (req, res, next) => {

            let q = q2m(req.query);
            
            if (req.query._id) {
                var ObjectId = require('mongodb').ObjectId;
                q.criteria["_id"] = ObjectId(req.query._id);
            }

            User.collection.find(q.criteria, q.options).toArray(function (err, data) {
                if (err)
                    return next(err);

                return res.status(200).send(data);
            });
        }));

from query-to-mongo.

pbatey avatar pbatey commented on July 20, 2024

It appears that this issue has been addressed.

from query-to-mongo.

Related Issues (18)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.