Mongoose How to show multiple results? - node.js

How to display multiple results with one query? I looked through mongoose's documentation. Function '.findByID()' return one 1 document. I am using it here:
router.route ('/friends/:id').get((req,res) => {
Friend.findById(req.params.id, (err,friend) => {
if (err) console.log(err);
else res.json(friend);
});
});
Now i would like to display all results which have in my second column "UserMain" by specified value. Mongoose offers functions like 'updateMany()' or 'deleteMany()' but I can not see 'findMany()' anywhere. I tried to do it in the that way, by passing just second columns value but nothing has happend.
Thank you for your time.
EDIT #1:
1
EDIT #2:
router.route ('/friends/:UserMain').get((req,res) => {
Friend.find({UserMain: req.params.UserMain}, function (err, friends) {
if(err) {
console.log(err)
} else {
res.json(friends)
}
})
});
EDIT #3 2

Try this:
router.route ('/friends/:UserMain').get((req,res) => {
Friend.find({UserMain: req.params.UserMain}, function (err, friends) {
if(err) {
console.log(err)
} else {
res.json(friends)
}
})
});

To retrieve many document within your database use find method which take as first parameter an object which represent clause with which to find documents that match that condition
Friend.find({ user_main: request.params.UserMain}, function (err, friends) {
if(err) {
console.log(err)
} else {
res.json(friend)
}
})

Related

native js how to find a field name of a collection where another field equal to certain value

I know that on robomongo if I want to find _id of user where username = test2 I can use
db.getCollection('user').find({},{_id:1},{"username":"test2"})
now, on visual studio code, I want to find value of field "disabled" from user collection where field "username" value equal to variable "tempusername" value. I tried:
colUser = mongoDb.collection("user");
var status = colUser.find({},
{ disabled:1},{ username:tempusername},function (err, doc) {
console.log(doc);
});
but it shows value of status is "undefined". What is the write code for this?
I think it's something you're looking for.
const url = 'mongodb://localhost:27017'
MongoClient.connect(url, (err, db) => {
const dbo = db.db('mydb')
dbo.collection('user').find({disabled:'1',username:tempusername}).toArray((err, doc) => {
if(err){
console.log(err)
}
console.log(doc)
db.close()
})
})
I found the answer, basically the way it work is the result will be return inside the function, so I have to put it like this:
var statusbuffer;
colUser.findOne({ username:tempusername},{ _id:0,disabled:1},function (err, userstatus){
// User result only available inside of this function!
if (err) {
next("Failed to update records");
} else {
console.log("disabled status here:",userstatus.disabled) // => yields your user results
statusbuffer = userstatus.disabled;
next();
}
});
thanks all for your comments!

Show entire MongoDB contents in Node.js API

First off, don't worry, it's a tiny data set - I realise it wouldn't be wise to dump an entire production DB to a single screen via an API... I just need to get a JSON dump of entire (small) DB to return via an API endpoint in a Node.js application.
My application does successfully return single records with this code:
MongoClient.connect("mongodb://localhost:27017/search", function (err, db) {
if(err) throw err;
db.collection('results', function(err, collection) {
// search for match that "begins with" searchterm
collection.findOne({'string':new RegExp('^' + searchterm, 'i')}, function(err, items){
// get result
var result;
if (items == null || items.result == null){
result = "";
}
else {
result = items.result;
}
// return result
res.send(result);
});
});
});
So I know Node is talking to Mongo successfully, but how can I tweak this query/code to basically return what you get when you execute the following on the MongoDB command line:
$ db.results.find()
This is snippet.
model.find({}).exec(function (err, result) {
if (err) {console.error(err); return;}
else return result;
});
First use your predefined model and call find. the logic is to place a empty object {} essentially rendering . select all from this model.
Make sense?
Exactly as you've described it.
collection.find({}).exec((err, result) => {
if (err) {
console.log(err);
return;
}
if (result.length > 0) {
// We check that the length is > 0 because using .find() will always
// return an array, even an empty one. So just checking if it exists
// will yield a false positive
res.send(result);
// Could also just use `return result;`
});
Thanks guys, I appreciate your answers pointing me in the right direction, in terms of using {} as the query. Here is the code that eventually worked for me:
db.collection('results', function(err, collection) {
collection.find({}).toArray(function(err, docs) {
res.send(docs);
});
});
The crucial element being the toArray(...) part.

what is the benefit to using mongoose .exec?

User.find().exec(function (err, users) {
if (err){
callback(err);
} else {
callback(users);
}
});
User.find(function (err, users) {
if (err) {
callback (err);
} else {
callback(users);
}
});
What is the benefit of using the top code? both seem to work equally well
They are identical and there's no benefit in your example
When you do not pass a callback to find function it won't execute but instead returns a query then you need to use exec()
var query = User.find();
now you can add some more criteria
query.where({age: 15});
and some more
query.select({name:1}); // or {firstname:1, lastname:1} etc.
now you've built up your query so to get the results you need to execute it.
query.exec(function(err, users){
});
But you can also do this like
User.find({age:15}, {name:1}, function(err, users){
});
Above is identical to
User.find({age:15}, {name:1}).exec(function(err, users){
});
since there's no callback in find function it will return query which means no results, exec will give you the results

Make Node.js code synchronous in Mongoose while iterating

I am learning Node.js; due to asynchronous of Node.js I am facing an issue:
domain.User.find({userName: new RegExp(findtext, 'i')}).sort('-created').skip(skip).limit(limit)
.exec(function(err, result) {
for(var i=0;i<result.length;i++){
console.log("result is ",result[i].id);
var camera=null;
domain.Cameras.count({"userId": result[i].id}, function (err, cameraCount) {
if(result.length-1==i){
configurationHolder.ResponseUtil.responseHandler(res, result, "User List ", false, 200);
}
})
}
})
I want to use result in Cameras callback but it is empty array here, so is there anyway to get it?
And this code is asynchronous, is it possible if we make a complete function synchronous?
#jmingov is right. You should make use of the async module to execute parallel requests to get the counts for each user returned in the User.find query.
Here's a flow for demonstration:
var Async = require('async'); //At the top of your js file.
domain.User.find({userName: new RegExp(findtext, 'i')}).sort('-created').skip(skip).limit(limit)
.exec(function(err, result) {
var cameraCountFunctions = [];
result.forEach(function(user) {
if (user && user.id)
{
console.log("result is ", user.id);
var camera=null; //What is this for?
cameraCountFunctions.push( function(callback) {
domain.Cameras.count({"userId": user.id}, function (err, cameraCount) {
if (err) return callback(err);
callback(null, cameraCount);
});
});
}
})
Async.parallel(cameraCountFunctions, function (err, cameraCounts) {
console.log(err, cameraCounts);
//CameraCounts is an array with the counts for each user.
//Evaluate and return the results here.
});
});
Try to do async programing allways when doing node.js, this is a must. Or youll end with big performance problems.
Check this module: https://github.com/caolan/async it can help.
Here is the trouble in your code:
domain.Cameras.count({
"userId": result[i].id
}, function(err, cameraCount) {
// the fn() used in the callback has 'cameraCount' as argument so
// mongoose will store the results there.
if (cameraCount.length - 1 == i) { // here is the problem
// result isnt there it should be named 'cameraCount'
configurationHolder.ResponseUtil.responseHandler(res, cameraCount, "User List ", false, 200);
}
});

MongoDB Node findone how to handle no results?

Im using the npm mongodb driver with node.
I have
collection.findOne({query}, function(err, result) {
//do something
}
The problem is say I dont have any results, err is still null whether I find a result or don't. How would I know that there were no results found with the query?
I've also tried
info = collection.findOne(....
But the info is just undefined (it looked asynchronous so I didn't think it was the way to go anyway..)
Not finding any records isn't an error condition, so what you want to look for is the lack of a value in result. Since any matching documents will always be "truthy", you can simply use a simple if (result) check. E.g.,
collection.findOne({query}, function(err, result) {
if (err) { /* handle err */ }
if (result) {
// we have a result
} else {
// we don't
}
}
All of these answers below are outdated. findOne is deprecated. Lastest 2.1 documentation proposes to use
find(query).limit(1).next(function(err, doc){
// handle data
})
Simply as:
collection.findOne({query}, function(err, result) {
if (!result) {
// Resolve your query here
}
}
nowadays - since node 8 - you can do this inside an async function:
async function func() {
try {
const result = await db.collection('xxx').findOne({query});
if (!result) {
// no result
} else {
// do something with result
}
} catch (err) {
// error occured
}
}
If result is null then mongo didn't find a document matching your query. Have tried the query from the mongo shell?
collection.findOne({query}, function(err, result) {
if (err) { /* handle err */ }
if (result.length === 0) {
// we don't have result
}
}

Resources