Find in MongoDB - node.js

Am trying to perform Login operation by checking the username and password are correct but the problem is if i check with find operation it just returns me the ID alone i want it to return the whole field for an instance if it is a match it should return me all the details of that particular user ex: username,email,password,DOB all the details. But my query returns only id. The query is
db.users.find({"email":"cool1nn#gmail12.com"},{"pasword":"1345"})
And If i perform via Nodejs it returns the Id and Password alone
userSchema.find({"email":req.body.email},{"password":req.body.pwd},function(err,item) {
if(err) throw err;
console.log("item " + item);
})

The first argument for find() is the query, the second argument is projection.
You are doing userSchema.find(query, projection) opposed to just userSchema.find(query).
You want
userSchema.find({ email: "cool1nn#gmail12.com", pasword: "1345" })
Also since you are looking for ONE item, use findOne() not find().
userSchema.findOne({ email: "cool1nn#gmail12.com", pasword: "1345" })

Related

Express, Mongoose, db.findOne always returns same document

I am attempting a CRUD app with MEAN stack. I am using mongoose in Express to call to the MongoDB. I am using the FindOne function with a specified parameter, and it's always returning the same (incorrect) document.
I know I am connected to the correct database, since I get a document back from that collection, but it's always the same document, no matter what I pass as the parameter.
module.exports = mongoose.model('Player', playersSchema, 'players'); //in player.js
const Player = require('./model/players');
app.get('/api/player/:id', (req, res) =>{
Player.findOne({id: req.params.playerId},
function(err, player) {
if(err) {
res.json(err);
}
else {
res.json(player);
}
});
});
I have 3 separate "players", with three distinct "playerID" fields (38187361, 35167321, 95821442). I can use Postman to GET the following URL, for example:
http://localhost:3000/api/player/anythingyouWantInHere
and it will return 38187361, the first document. I've been over this website, many tutorials, and the Mongoose documentation and I can't see what I'm doing wrong..
I'd like to eventually find by playerId OR username OR email, but one hurdle at a time...
From the mongoose documentation of findOne, if you pass Id a null or an empty value, it will query db.players.findOne({}) internally which will return first document of the collection everytime you fetch. So make sure you are passing non-empty id here.
Note: conditions is optional, and if conditions is null or undefined,
mongoose will send an empty findOne command to MongoDB, which will
return an arbitrary document. If you're querying by _id, use
findById() instead.
Your route is '/api/player/:id', so the key on the req.params object will be 'id' not 'playerId'.
I don't know what/where/if you're populating the playerId param, but if you update your query to call req.params.id it should actually change the document based on the path as you seem to be wanting to do.
I had the same problem, and it was that the name of column's table was different from the model I had created.
In my model the name of the wrong column was "role" and in my table it was "rol".

Skip fields on collection.find() not working

I'm developing a report system in Node.JS and MongoDB
I'm trying to make a query to get some datas from the MongoDB, but the query don't specify all the fields that the collection have
(example, in the query I'm asking for the field typ, event and date, but in the collection I have more than 10 fields).
db.collection('logs').find({
system: {
type: query.logType,
event: query.event,
date: query.date
}
}).toArray(function (err, document) {
if (err) throw err;
console.log(document);
});
This way, it doesn't return anything, but when I specify all the fields that the collection have, the query works.
Is there any way to use RegEx or skip the other not-needed fields on the query?
you can use map and select properties in that function
let tmp = [{id:1,name:"aaa"},{id:2,name:"bbb"}].map((item)=>{
// your can make new object here
return {name: item.name};
});
console.log(tmp);

Strange result when nesting query of two different collections

I have a need to check two separate collections in Mongo to see if a phone number exists.
I first created a global variable called 'ownerId'
I then look in one collection call 'Profile'. If the email value I pass exists in the 'emails' array of a document in that collection, I fill the 'ownerId' variable I created with a value in that document called 'owner_id'.
I then look in another collection called 'User', which has a single email field. If the email value I pass exists in a document in that collection, I fill the 'ownerId' variable I created with the '_id' of that document.
I have my queries nested in a couple 'then()' statements.
Here is my code:
Profile.findOne({'emails.email_address':req.body.invited_email}, function(err, result){
if(result)
ownerId = result.owner_id;
}).then(function(){
User.findOne({'email':req.body.invited_email}, function(err, result2){
if(ownerId !== null)
ownerId = result2._id;
})
}).then(function(){
console.log(' --------------- THIS IS AN EXISTING EMAIL OWNER ID: ' + ownerId);
})
The result is not as I expect.
If the 'Profile' query is true and finds a match, then it will console log the ownerId with a value.
If the second 'User' query is true, but there is not match for the 'Profile' it will console log 'null'. I expect it to console log the _id value of the User result.
Can anyone see the error in my logic?
I wouldn't mix callbacks and promises. I would recommend using async/await for this. It makes asynchronous code look synchronous. For example:
let owner_id;
try {
let profile = await Profile.findOne({ 'emails.email_address': req.body.invited_email });
let user = await User.findOne({ 'email': req.body.invited_email }):
if (profile) {
owner_id = profile.owner_id;
} else if (user) {
owner_id = user.owner_id;
} else {
console.log('no owner id found');
}
} catch(err) {
console.log(err);
}
The code is wrapped in try/catch to handle errors, just like the catch() method for ordinary promises. The functions using await needs the async keyword.
await is used to wait for promises to finish. No callbacks are needed. You can see the code looks like ordinary synchronous code.

MongoDB/Mongoose returning empty array

I'm currently working on a project with mongodb/mongoose, and every time I purposely query for something that does not exist in the DB, I am getting a response with an empty array. This is my code for using Express to set up an API and return the data found in the DB:
app.get('/api/:id', function(req, res) {
var id = req.params.id;
Job.find({jobID: id}, function (err, foundJob) {
if (err) {
console.log(err);
}
else {
res.json(foundJob);
}
});
});
However, every time I go to localhost:3000/api/67 (I have no object with jobID: 67 in the database yet), the console does not print the error. It gives me a JSON response with an empty array. Any ideas to why this is happening? The weird part is that when I change jobID: id to _id: id, it does give me an error. Why doesn't it do that for the jobID field?
EDIT: Just to clarify, the reason why I do not want this behavior is because my program will never print the error, even if a job in my DB doesn't exist with that specified jobID.
It does something different than you think it does.
Job.find({jobID: id}, ... )
What this really says is give me array with all the documents in collection "Job" that have field "jobID" equal to some value.
What if there is no such document? Well, then the array will be empty. Without any error, of course, what should be an error here? You asked for all documents (given some filter) and an array with all such documents was returned. It is just a coincidence that the size of the array is zero, because there are no such documents.
If you want to check whether there is no such document then check whether the array is empty.
I don't know why it is giving you error when you change JobID to _id; what error exactly is it?
If you are interested only in one document, then there is method findOne that returns only the first document (or null if no such documents exist) instead of an array.
About error when you try to find something by it's __id: It gives you a error because __id is not String, it's ObjectId. So you should search for document with that __id like this: _id: ObjectId(id)
About empty string: If you want to display some kind of different message you should check if db returned something or is it rather empty string that got returned. Something like this:
app.get('/api/:id', function(req, res) {
var id = req.params.id;
Job.find({jobID: id}, function (err, foundJob) {
if(foundJob){
res.json(foundJob);
}else{
res.json("nothing found");
}
if (err) {
console.log(err);
}
});
});
Edit: I didnt realize that you had check for error, I changed code.
Returning an empty string is normal behavior for mongoose. You should handle your response like this:
if (err) {
//handle error
} else if (foundJob) {
//work with your data
} else {
//nothing was found
}
The error you get with _id must be irrelevant and is probably due to an invalid query.

CloudantDB: using db.get without id

I have a table:
id: 001
name: test
provider_id:ABC123
and I try to query with provider_id and get a error message, but not with id:001
db.get("ABC123", function(err, data) {
// The rest of your code goes here. For example:
console.log("Found id:", data);
});
Please give me your thoughts how to run successfully db.get + provider_id
You can't use db.get without the ID. However you can use either Query or Views to find the document you are looking for.
With query you can use a selector such as {"provider_id":"ABC123"} to find the documents which contain that provider id.
With views you can use the provider_id as the key and the doc id or null as the value, such as:
function (doc) {
emit(doc.provider_id, doc._id);
}
If you are using null as the value, you should use the include_docs=true option for the request. See your library's documentation on how to use views and query.

Resources