FindOne NODEJS mongoDB - node.js

I have this code that check for me if the token provided is valid or not, the code is working but the problem that it is returning wrong id, => it returns the first Id that he found in the database
the code that I'm using is this
const checkToken = async (req, res ,next) => {
const token= req.body.token //the token is mix of number and letters lenght (6)
User.findOne(token,
(err, user) => {
if (err) {
const error = new Error('Token not Found');
error.status= 406;
return next(err, error);
}else
{
res.send('/api/users/'+ user.id +'/update') // u need to mention user.id from DB
}
})
this is my image of the database :
I don't want to use the id to search the token , what I want is use the provided token and search in DB if it is found so I retrieve Id

According to MongoDB documentation that is the usual behavior of findOne method. When multiple documents satisfy the condition the function returns the first document that is written first. Reference
To check use find() and see all the documents it returns for the correct id and to use findOne make sure the token is unique for all the document.

Related

MongoDB: findOne not working as expected?

I'm creating an API to my database of coins and I don't want to add duplicate coins to my database so I've created this line of code in my function
const addCoin = async (req, res) => {
const { coinId, seconds, bidAmount } = req.body;
console.log(coinId);
const coinExists = await Coin.findOne({ coinId });
console.log(coinExists);
if (coinExists) {
res.status(400).send({ message: 'Coin Exists Bad Request' }); // bad request
throw new Error('Coin already exists');
}
In my Postman I am inputting a different coinId in the request body and I am getting the error that Coin Exists?
Is findOne here not working as expected?
Confused.
Thanks
Ahh after some documentation reading
I have to specify which property in the Coin Model I want it to find specifically
so in this case
I did
Coin.find({ itemId: coinId})
Since in my model its defined as itemId but user input is coinId

How to get a collection that is in a document of another collection in firebase

So I am creating an API in firebase and in the database there is a collection of universities. Inside this collection there are multiple documents of universities. In each document I've created a collection of users. So inside every university you can see the users that attend this uni.
What I want to do is everytime I make a request to the server by GET of api/user it shows (through authorization token) my details as a user.
I have created the function that requests the data of a user, by using the Bearer {token} but it seems that, when I console log the university ID is undefined. Inside the user document there is a field called uniId (the id of the university the user belongs and it is the same ID of the university document). I am using postman to make the API requests after I have created the Bearer token with another login function.
exports.getAuthenticatedUser = (req, res) => {
let userData = {};
db.doc(`/unis/${req.user.uniId}/users/${req.user.handle}`).get()
.then((doc) => {
if(doc.exists){
userData.credentials = doc.data();
return res.json(userData);
}
})
I understand that I need to change something in "req.user.uniId" because now that variable is undefined.
Any guidance on how I can approach this?
One option is to add a userhandle field to your documents so you can use a collection group query. Something like this:
exports.getAuthenticatedUser = (req, res) => {
let userData = {};
db.collectionGroup('users').where('userhandle', '==', req.user.handle)
.limit(1)
.get()
.then(function (querySnapshot) {
querySnapshot.forEach(function (doc) {
userData.credentials = doc.data();
return res.json(userData);
});
}).catch(function(error) {
console.log("Error getting documents: ", error);
})
}

Remove by id in mongoose

I'm struggling with removing record from my database via api.
First I get whole record from the API, and then when record is not filled the way I want I have an option of removing it by front end. I pass the object ID and want to remove it using mongoose method. However, no matter how I pass the id i cant seem to delete the record.
Here is the code of the remove route:
router.delete('/database/delete/', (req, res, next) => {
let id = 'ObjectId("'.concat(req.body.id).concat('")');
let id2 = req.body.id;
console.log(id, id2)
db.findByIdAndRemove(id).then((err, client) => {
console.log(client)
if (err) return res.status(500).send(err);
const response = {
msg: "Client removed",
success: true
}
return res.status(200).send(response);
})
})
As you can see im trying to pass the id both ways, so the console log outputs both: ObjectId("5a8ea050fe07b60eda004c6e") and 5a8ea050fe07b60eda004c6e, both wont work. How can i solve this?
var mongoose = require("mongoose")
const ObjectId = mongoose.Types.ObjectId;
var id = ObjectId("5a8ea050fe07b60eda004c6e")
//for your case
let id2 = ObjectId(String(req.body.id))
console.log(typeof id) //it will show object
What you are doing is trying to make your id look like ObjectId. If you will check typeof id it will be string instead of object,

How to query for an array of users in my users collection in mongodb using mongoose?

I have a collection of some users (along with their contact numbers) registered in my node and mongodb app.
Now I have an array of contact numbers. I want to get an intersection of this array and the users in my app. How to do it, since I cannot take each number and check for it's existence in the database. Any help/link would be helpful. Thanks in advance.
You can use the $in operator. It would really help if you at least provided some code, like your schemas, previous attempts etc.
Here is an example of how to do ii assuming you are using mongoose, and have a user schema with a number property and an array of numbers.
User.find({ number: { $in: numbers } })
.then(function (docs) {
// do something with docs here;
})
.catch(handleErr);
This can be done simply using promises. I am assuming you have an array of contact numbers and a collection Users which has field contact number. The below function will get you the list of all the Users with contact numbers listed in the array. I am assuming that the User model is available and the contact array is being passed as a function argument. Basically this function will loop through the contact list array and find any user with that contact no in the user collection and return a promise. All the promises are being pushed into an array and the promise will be resolved only when all the async operations have completed resulting in either success or error.
// import User from User-model-defition
function getUsersByContact(contactArr) {
return new Promise((resolve, reject) => {
const data = [];
const errors = [];
contactArr.map(id => {
User.findOne({ contact_no : id })
.then(response => {
if (response.user) { //checking if the response actually contains a user object
data.push(response.user);
} else {
errors.push(response.error);
}
if (contactArr.length === data.length + errors.length) {
//this makes sure that the promise will be resolved only when all the promises have been resolved
resolve({ data, errors });
}
})
.catch(error => reject(error));
})
})
}

Retrieve unique ID from MongoDB using Express.js

I'm fairly new to MongoDB. My current code is as follows:
var app = express();
app.post('/myDB', function(req, res) {
console.log('POSTed data');
db.myDB.insert(req.body, function(err, doc) {
console.log(err);
res.json(doc);
});
})
I know that when data is inserted into MongoDB, a unique _id key:value pair is created. I would like to have access to this unique id upon data insertion.
But from what I know currently (admittedly not a whole lot), I would have to do an app.get('/myDB/:id')... (Or something similar) in order to access that unique identifier. Is there a way to do this without having to make an extra http request?
In MongoDB, with the Node.js driver, you can get the inserted id from the callback function's second parameter. The syntax is:
collection.insert(docs[[, options], callback])
where docs is a single document object or an array of documents, options is an options object and callback is a callback function to run after the record is inserted. The second paramter returns an array of documents inserted.
Thus you can retrieve the inserted id this way:
var app = express();
app.post('/myDB', function(req, res) {
console.log('POSTed data');
db.myDB.insert(req.body, {w:1}, function(err, doc) {
console.log("Record added as "+ doc[0]._id);
res.json(doc);
});
You can read more on the docs here.

Resources