안홍경
안홍경

Reputation: 43

Mongo DB query in Node.js

I want to create a query that finds the last insert that I have found.

Here is my dataset in Infos collection.

{
    "_id": "5c7114339624d8dd041bae18",
    "user_id": "AHK",
    "gps": "gps information",
    "timestamp": "2010-05-30T20:07:35.000Z",
    "__v": 0
},
{
    "_id": "5c7114bde3075ae0b38ec0bc",
    "user_id": "AHK",
    "gps": "gps information2",
    "timestamp": "2010-05-30T20:07:35.000Z",
    "__v": 0
},
{
    "_id": "5c7114c2e3075ae0b38ec0bd",
    "user_id": "AHK",
    "gps": "gps information3",
    "timestamp": "2010-05-30T20:07:35.000Z",
    "__v": 0
}

For example, I want to select the data which gps value is "gps information3".

It is the last inserted query In this DB. So I create query like below to select this.

router.get('/infos/gps/:userid/recent',function(req,res){

    var temp = Info.find({user_id: req.params.userid}, function(err, info){
        if(err) return res.status(500).json({error: err});
        if(!info) return res.status(404).json({error: 'user not found in Info collections.'});

    }).sort( {"_id": -1} ).findOne(function(err2,info2){
         if(err2) return res.status(500).json({error: err2});
        if(!info2) return res.status(404).json({error: 'findOne error'});
        console.log(info2.user_id +" "+info2.gps+" "+info2.timestamp);
        res.json(info2);

    });
});

It worked. But I don't understand the flow. I know that Nodejs is asynnchronous. And it has callback function.

As I guess, First, the find function is called, then sort function is called when the result of find function returned , and finally findOne function is called when the sort function is returned.

But I think that it isn't asynchronous. Because I thought sort function would proceed before the results of the find function were returned.

Could you tell me what is the answer?

In addition, let me know if there is a way to make this query better.

Last, Can mongodb's _id attribute be the reference point when sorting with time?

I'm a beginner so I have too many questions. I'm sorry.

Upvotes: 0

Views: 80

Answers (1)

Radu Luncasu
Radu Luncasu

Reputation: 1073

in mongoose you either:

  • use a query with a callback, if you pass in a callback function, Mongoose will execute the query asynchronously and pass the results to the callback
Info.find({},callbackFunc);
  • use a query without a callback and this allows you to chain multiple queries. At the end of the chain you add .exec(callbackFunc) to execute and pass the results to the callback
Info.find({user_id: req.params.userid}).sort({"_id": -1}).findOne().exec(callbackFunc)

the callback functions are something like this:

function callbackFunc (err,docs) {
if (err) {
  console.log(err); // do something
 }
if (!doc) {
  // do something else
 }
console.log(doc); //do the main thing
}

Frankly, I have no idea how the code you posted works, but if it does, it's definitely not supported. https://mongoosejs.com/docs/queries.html

As to why you can sort by id and get it sorted in chronological order, that's because in MongoDB we get a timestamp for free if we define our primary key as an ObjectId. This is because the 12 byte ObjectId type contains a 4 byte time component. http://www.syntaxsuccess.com/viewarticle/sorting-by-objectid-in-mongodb

Upvotes: 1

Related Questions