I’m new to mongodb and trying to figure out sorting with MongoClient in a node.js/express application.
This works in the mongo command line client:
db.mycollection.find().sort({"date":-1}); // displays by date, newest to oldest
I’m trying to achieve the same thing in my application:
db.collection('mycollection').find().sort({"date":-1}); //order remains the same
How can I achieve the same result as the first query? Thank you.
So, first, I'd recommend using Mongoose. Failing that, however, the Node MongoClient puts things like sorting into the find() arguments, like so:
db.collection('mycollection').find({}, {sort:{date:-1}});
Related
I am trying to query an old mongoDB collection in node.js with the native driver.
It uses Legacy UUID as its _id field.
In my code I am using Binary values such as: "2u0kLwUZuEWQvjqOjgQU4g=="
and I want to query the collection with find() operation.
When trying to test it directly with mongoDB I am able to use the following query:
db.getCollection('myCollection').find({_id: BinData(3, "2u0kLwUZuEWQvjqOjgQU4g==")})
to find my item.
But what I need to do is to find multiple items.
So I need to use something like this:
db.getCollection('myCollection').find({_ids: { $in: [BinData(3, "2u0kLwUZuEWQvjqOjgQU4g=="), BinData(3, "3u0kLwUZuEWQvjqOjgQU4g==")...]}})
but it does not seem to work and always returns zero records.
I am not sure why? and what might be the correct way to query multiple Legacy UUIDs?
Dear stackoverflow community,
I usually no make posts here, but in this time i ask myself why not?, after 2 hours without getting a solution.
This one is pretty basic but involves a specific json model, mongoose, mongodb and nodejs.
Now the problem, is that i´m trying to get the data for the user_ppal_id : 1 and the exam_design_id : 1 , the search of the user_ppal_id succeeded, but the exam_design_id that is into a nested array always returns to me the value 1 and 2 (and i´m passing by parameter the exam_design_id 1)...
This is my model, My nodejs rest method and how i´m using mongoose, nodejs and mongodb, My moongose model, A better view of the model from Umongo Ide:
SEE THE IMAGE HERE BECAUSE I AM NEW IN STACKOVERFLOW
All the structure is working, but the data from result is not the one i expected. You can check the response of this rest service by just clicking this url: http://207.244.75.230:8000/dyntestreports/getExamReport?idUserPpal=1&idExamDesign=1
In the response i´m getting the exam_design_id data for values 1 and 2 when i pass just the value 1.
Actually i tried with the following mongo queries and i not succeed:
1) ExamReportByUser.find({'user_ppal_id':userPpalId,'exams_created': {$elemMatch:{'exam_design_id': {$eq:examDesignId}}}}
2)ExamReportByUser.find({'user_ppal_id':userPpalId,'exams_created.0.exam_design_id':examDesignId}
At this moment i don´t know what i´m doing wrong even from a mongo console query i can´t get it works for just exam_design_id = 1 data.
I´m sure it could be a simple error but i´m not seeing it at this moment.
I really hope you can help me guys. Thanks in advance! Have a nice day.
My bad! I just have found the solution... And i post it here for anyone that had the same doubt... The code querying the data should be like this (it was just keys syntax, basic mongo):
ExamReportByUser.find({'user_ppal_id':userPpalId},{'exams_created': {$elemMatch:{'exam_design_id': examDesignId}}},'id user_ppal_id exams_created exam_design_id user_submitted_exam',function(err, result) { if (err) return console.log(err); return res.send(result); }); };
Now i´m getting the data of user 1 and exam_design 1.
I will not select this as an answer, waiting for the specialists ;)
I am trying to query directly on mongo using sails native adapter. I am not getting any result inspite of document present in db. Direct Waterline find functions returns documents. However I want to use native find for some other purpose and trying to make it work. Any suggestions? Output of below : null [].
User.native(function(e,collection){
collection.find({phoneNumber:mPhoneNumber}).toArray(function(e,r){console.log(e,r);});
It worked. Seems orm native does not convert number in string format to integer while querying. Converted mPhoneNumber to Integer using parseInt and it worked.
Here is the updated code
User.native(function(e,collection){ collection.find({phoneNumber:parseInt(mPhoneNumber)}).toArray(function(e,r){console.log(e,r);});
Can someone please stop me from going insane!
I have a MongoDB database which has a simply database that was created and populated via Mongoose, this works great I can perform finds woth no problems at all.
I went into the Mongo console and created a new database with just use newDB and the performed a simple insert, I inserted several records and they appeared fine within Mongo. I can find on them and so all the Mongo operations but when I try to perform a find on this database Mongoose returns a null???
I have noticed that the database I created in Mongo console does not create the '__v' field which I believe is for Mongoose internal indexing uses, I have created this field in my custom tables but still no joy I just cannot create data from outside of Mongoose and use it within my app??????
I have spent hours looking into this and reading maybe I just missed something but honestly I cannot find a thing on this and many people must hit this every week????
**Sorry here is the code I am running against the database:
exports.adduser = function(req, res){
var mongoose = require("mongoose");
mongoose.connect("localhost/nm", function(err){
if(err)throw(err);
console.log("Connected to MongoDB successfully...")
var schema = mongoose.Schema({
Firstname: String,
Lastname: String,
MiddleInitial: String,
Password: String,
Username: String
});
var auser = mongoose.model("Users", schema);
auser.find({}, function(err, alist){
console.log(">>>>"+alist);
});
});
**
Thanks again!!!!! for your input it is very much appreciated....
try inspecting mongo instance with
show dbs
use <dbName>
in mongo shell to make sure you are using the right database and then
show collections
or alternatively
db.getCollectionNames()
To see if your collections are there or not.
__v is a document version property incremented only for array operations(mongoose 3).
Your connection string might be wrong.
Anyone experiencing this problem and I know there are a good few read the comment by robertklep above it solved my problems very quickly!
DOnt know how the accept a comment sorry!
Why would a database named 'blog' not allow a record insert and also give no return error and why would a database named 'blogs' allow a record inserts and return errors?
I just spent several hours going through all my code thinking I did something wrong. I have written many mongoose connected apps but when using the following it would return success but not insert the record and return no error as to why:
mongooose.connect('mongodb://localhost:27017/blog');
After banging my head against a wall for a bit I decided to change the database name:
mongooose.connect('mongodb://localhost:27017/blogs');
It works! But why would this name convention matter? I can't find anything in the documentation for MongoDB or Mongoosejs.
So I'm fairly certain mongodb doesn't care about database name "blog" vs "blogs". However, do note that mongoose has the questionably-helpful feature of silently queueing up operations while the database connection is still not established and then firing them off if/when the database connection is ready. That could be causing your confusion. To test that theory, pass a callback to mongoose.connect and put a console.log in the callback so you know exactly when the connection is ready.