Why am I getting an "undefined" result from my MongoDBQuery in Node? - javascript

I've already stablished a DB with it's schema like this:
When I use my search function in Nodejs it works perfectly and returns my info like this:\
So, why is is than when I try to fectch my user from mongodb and get the parameter "examenes":
I get this undefined return?:

The problem is you are not using await so in the line console.log(user.examenes) the variable user is not the data returned by mongo; is another object without attribute examenes. And trying to access the value is undefined.
So you can use:
let user = await (usuario.findOne({_id: req.params.id}))

Have you added mergeParams in your router?
This options adds params object to the request
const router = express.Router({ mergeParams: true });
then
/predict/:id results in req.params.id
By default this option is disabled in express

I think you should use the await keyword
try{
var user = await model.findOne({ _id: req.params.id});
} catch (e) {
// Handle Errors
};
Or
model.findOne({ _id: req.params.id}).then(result => {
var user = result;
}).catch(e=> {
// Handle Errors
});

Related

retrieving data from database according to query conditions

"_id":{"$id":"61b5eb36029b48135465e766"},
"name":"push-ups","link":"https://google.com",
"image":"https://google.com",
"gender":["0","1","2"],
"goal":["lw","gw","sf"],
"age":60,
"excersietype":"chest",
"__v":0
this is how my data is stored in database
and I want to fetch data according to 3 condition
I got 3 queries from front gender goal and age and according to that I have to retrieve data
const gender = req.query.gender;
const age = req.query.age;
const goal = req.query.goal
const level = req.query.level
if (level==='fb'){
const getdata = new Forbeg.find({gender:{$in:gender}},{age:{$lte:age}},{goal:{$in:goal}});
console.log(getdata)
}
Is this a good way to find the data because I am getting error
UnhandledPromiseRejectionWarning: MongooseError: `Model.find()` cannot run without a model as `this`. Make sure you are not calling `new Model.find()`
I am getting above error while fetching
The error is explicit : Make sure you are not calling 'new Model.find()'. Use const getdata = Forbeg.find(...).
However, you will immediately run into the next problem, as Mongoose models return thenables (Promise-like). console.log(getdata) will log Promise<pending>. You need to resolve your database call, either by doing
Forbeg.find(...).then( getdata => console.log(getData));
or (much more better!):
const getdata = await Forbeg.find(...);
console.log(getdata)
Even better, add .lean() to get simple JSON data instead of an array of Mongoose objects (faster), and .exec() to get a true Promise instead of a thenable :
const getdata = await Forbeg.find(...).lean().exec();
console.log(getdata)
Remove new operator
const getData = Forbeg.find({gender:{$in:gender}},{age:{$lte:age}},{goal:{$in:goal}});

get id value from req.body.id for new value of object

I have a field with id value in it. It auto created while created a new data. Concatenated with string. I have doing a try, but it gets undefined value.
code:
const { id, nm_acara, tugas, nm_petugas } = req.body;
const result = await prisma.dinas.create({
data: {
kd_dinas: `D-${id}`,
nm_acara,
tugas,
nm_petugas,
rundown: "/texts/" + req.file.filename,
},
});
result:
Do you sure you sent the id property to the server? or was it just created by the ORM?
I think your code is correct
But likely id was not sent properly
So, u should check the existence of id firstly
const { id, nm_acara, tugas, nm_petugas } = req.body;
console.log(id) // print the id
If id still undefined => this issue occurs in client side
make sure are you using the below lines for parsing application/json!?
app.use(express.json());
app.use(express.urlencoded({extended:true}));
console.log the req.body for check are you getting id or not.

Async Storage retrieve value of key in item

I'm new to Javascript and react native, and the question itself will be probably very easy to answer.
I'm setting up a AsyncStorage and creating a Item inside the storage, which is a .JSON that has 3 key values to it.
const saveDataToStorage = (token, userId, expirationDate) => {
AsyncStorage.setItem('userData', JSON.stringify({
token: token,
userId: userId,
expiryDate: expirationDate.toISOString()
}))
};
What I want to do now is to retrieve the "userId" value from this item in an other part of the project but here is the problem.
var PersonalId = await AsyncStorage.getItem('userData');
console.log(PersonalId);
console.log(typeof PersonalId);
I know how to access the item itself, but I have no clue how to access the special key inside it. I can not use the command:
var PersonalId = await AsyncStorage.getItem('userData').userId;
because the item from the AsyncStorage is a string, I know this because I got this info from the second line of my code.
console.log(typeof PersonalId);
How can I access the special key "userId" inside my item "userData" and not the whole item itself? I cant work with the item anyways because its a string, I can not treat it as an object and thats my problem.
Thank you for reading and helping out!
You need to first parse value you are getting from the AsyncStorage into a JSON object using JSON.parse(). Try this implementation.
const get_data = async () => {
const userData = await AsyncStorage.getItem("userData");
const userObject = userData !== null ? JSON.parse(userData) : {};
const personalId = userObject.userId;
console.log(personalId);
};
You are forgetting that you stringified the JSON before saving it to storage.. so you are getting string when you read it. Simply JSON.parse the returned string and you should be on your way.
const userData = await AsyncStorage.getItem('userData');
const personalId = JSON.parse(userData).userId;
You should also wrap the above code in a try-catch to make sure you catch errors when invalid data is tried to be parsed and it throws an error.

Firestore retrieve single document by field value and update

I'm trying to retrieve a single document by a field value and then update a field inside it.
When I do .where("uberId", "==",'1234567'), I am getting all the docs with field uberId that matches 1234567.
I know for sure there is only one such document. However, I don't want to use uberId as the document's ID, otherwise I could easily search for the document by ID. Is there another way to search for a single document by a field ID?
So far, reading the docs, I could see this:
const collectionRef = this.db.collection("bars");
const multipleDocumentsSnapshot = await collectionRef.where("uberId", "==",'1234567').get();
Then I suppose I could do const documentSnapshot = documentsSnapshot.docs[0] to get the only existing document ref.
But then I want to update the document with this:
documentSnapshot.set({
happy: true
}, { merge: true })
I'm getting an error Property 'set' does not exist on type 'QueryDocumentSnapshot<DocumentData>'
While you may know for a fact there's only one document with the given uberId value, there is no way for the API to know that. So the API returns the same type for any query: a QuerySnapshot. You will need to loop over the results in that snapshot to get your document. Even when there's only one document, you'll need that loop:
const querySnapshot = await collectionRef.where("uberId", "==",'1234567').get();
querySnapshot.forEach((doc) => {
doc.ref.set(({
happy: true
}, { merge: true })
});
What's missing in your code is the .ref: you can't update a DocumentSnapshot/QueryDocumentSnapshot as it's just a local copy of the data from the database. So you need to call ref on it to get the reference to that document in the database.
async function getUserByEmail(email) {
// Make the initial query
const query = await db.collection('users').where('email', '==', email).get();
if (!query.empty) {
const snapshot = query.docs[0];
const data = snapshot.data();
} else {
// not found
}
}

how to access json data os asyncStorage function

I am using AsyncStorage to store data. Here is my function of storing data :
const profile = { userId, name, email };
await AsyncStorage.setItem('userProf', JSON.stringify(profile));
I have a problem when I try to access the data , if I console.log:
async componentWillMount(){
const profile = await AsyncStorage.getItem('userProf');
console.log(profile);
}
{"userId":"jefla3E0tjcJHhHKJK45QoIinB2","name":"egfgege","email":"ergeg#egrge.com"}
Now if I am willing to get only email value , I have tried with:
console.log(profile.email);
console.log(profile[0].email);
None of them worked, I get undefined as output, could you please help.
As AsyncStorage take and returns a string you will need to parse the string into json. You're already using JSON.stringify to save your object, you need to do the reverse operation to get it back to being an object.
const savedProfile = await AsyncStorage.getItem('userProf');
const profile = JSON.parse(savedProfile);
Then you should be able to access it the properties as you normally would, for example
const userId = profile.userId;
const email = profile.email;
const name = profile.name;
You may want to make sure that you perform a check that the returned value from AsyncStorage isn't null, as that will cause problems for you. Also await functions can throw, so you should make sure that you wrap your call to AsyncStorage in a try/catch
async componentWillMount(){
try {
const savedProfile = await AsyncStorage.getItem('userProf');
// you should check that the savedProfile is not null here
const profile = JSON.parse(savedProfile);
const userId = profile.userId;
const email = profile.email;
const name = profile.name;
} catch (err) {
console.warn(err);
}
console.log(profile);
}
When storing the value with AsyncStorage.setItem( ... ), you use JSON.stringify to convert the complete object into a String. This means, if you want to have a "normal" Object back (to use the dot operator), you have to use JSON.parse:
const profile = await AsyncStorage.getItem('userProf');
console.log(JSON.parse(profile));

Categories