Set an property to object after query.exec() - javascript

I am using node express. I am trying to populate a field which is populated from another field. But I was having problem so I tried to get the value from another query and then set it to the object I was sending.
api.get('/:id', authenticate, (req, res) => {
let query = MobileTranscation.findById(req.params.id)
.populate('sender')
.populate('created_by');
query.exec((err, datas) => {
if(datas.sender && datas.sender.parent) {
User.findById(datas.sender.parent, (err, user) => {
datas['parentName'] = user.username;
console.log(datas);
res.json(datas);
});
} else {
res.json(datas);
}
});
});
Here, I want to get username from MobileTranscation.sender in which sender has a parent property which has the username property. I was trying to populate sender and then take the parent id and search User with that and get the username. Problem I am facing is that if I log datas.parentName I can see I got the username, but when I am sending datas, there is no parentName property. What I am doing wrong here?
And is it possible to populate a property and then populate one of that populated property?

Whenever you do findById mongoose actually sends some kind of immutable object in return. So you cannot add an extra key to the object. You actually can use the .lean function. Like query.lean().exec((err, data) => { /** Function body* */ }). Now you can add extra keys you want.

Related

Using Lambda with Nodejs Count Some queries in Dynamo DB

After using the below to pull data from Dynamo db sucessfully
async function pullone(sessionid) {
const params = {
TableName: dynamodbTableName,
Key: {
'sessionid': sessionid
}
};
return await dynamodb.get(params).promise().then((response) => {
return response.Item
}, (error) => {
console.error('Do your custom error handling here. I am just gonna log it: ', error);
});
}
Instead of 'return response.Item' i just want to return the count instead.
I tried doing count(pullone(sessionid)) but not sure if that is even a valid method. Please assist
Not sure if I understood your question, but:
Since you're requesting data associated with a primary key, you'll get either 0 or 1 element in Item.
So, if you aim to know if "you've found something or not", you can use Number(response.Item != null) and you'll get 1 in case of "something" and 0 in case of "nothing".
If, instead, your data contains a "count" attribute, then (await pullone(sessionId)).count should work.
Otherwise, you have to query your DB (but you'll get Items (plural) in your response) and use the length() function of the Items array you'll get in the response.

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.

How to pass data of an object to HTML file

I have few posts in my app, and I want that when user selects one of them, he to be redirected to a Post.html page which contains all details about that specific product. I have two methods, createPost() for creating a product dynamically where I pass postId in order to keep track of that product, and getPosts() to get the posts from database. I am saving all posts in an array in localStorage to have data about the selected product in Post.html. I added an addEventListener() but not sure how to use it. The problem is that I am stuck how to get the information of that post and pass it to Post.html.
function getPosts() {
firebase
.firestore()
.collection("products")
.get().then(snapshot => {
let products = [];
snapshot.docs.forEach((doc) => {
products.push(doc.data());
createPost(
doc.data().title,
doc.data().description,
doc.data().price,
doc.data().postId
);
});
localStorage.setItem(`${products}`, JSON.stringify(products));
})
.catch((err) => {
console.log(err);
});
}
function createPost(title, description, price, postId) {
let div = document.createElement("div");
div.setAttribute("class", "product-home-show");
......
div.appendChild(divSellerRoundImage);
div.appendChild(divSellerName);
div.appendChild(divProductDescription);
div.appendChild(divProductName);
div.appendChild(divProductPrice);
productsCollection.appendChild(div);
div.addEventListener("click", function () {
// console.log(localStorage.getItem());
// window.location.href = "post.html";
});
}
You can get data from localStorage on another page. Use localStorage.getItem(keyName); Also keep in mind the first argument to setItem is the key name. I'd recommend changing your code to: localStorage.setItem("products", JSON.stringify(products));. Then you'll be able to retrieve your product list with they key "products."
Also, if you're saving an object, you'll need to parse it since it will be saved as a string. You can use JSON.parse
For example:
var retrievedData = localStorage.getItem("products");
var productListObject = JSON.parse(retrievedData);
You can save the selected post ID in another value in local storage, or a cookie. Lastly, you may want to consider using sessionStorage if you don't need the data stored after the session is over. See this link for more information

Update document in Mongoose (update array property at specific index)

I'm currently practicing my node.js skills and I am making a top10 movie list on a user's profile page. The user picked ten movies and now I want to save these movies in a user document in my database. This however, isn't working the array is still empty (I was able to change the 'picked' property to true though). Can anyone tell me why? Here is the code on the server side:
router.get('/updateTop10', function (req, res, next) {
// the string that I want to add to the db array
var movieElement = req.query.movieElement;
// the specific index of the array (the position of the movie in the top10
var index = req.query.index;
// the user that is currently logged in
var user = req.user;
User.findOne({'username': user.username }, function (err, user) {
// I am able to switch picked to true
user.top10.picked = true;
// However my array is still empty after I run the code
user.top10.top10[index] = movieElement ;
user.save();
res.send("SUCCESS")
} )
});
This is the structure of the user document:
Refer to https://github.com/Automattic/mongoose/issues/2654
Do this
user.top10.top10.set(index, movieElement);

Get json array from sub mongoose query

I have a sub query in mongoose need to get array out of sub query and attach to main json out put/ object.
my first query get user info which contains blocked_users array which is nothing but array of user id's.
i my second query we get profile details of blocker_users array and append to main user object in blocked_users.
var userId = ObjectID(req.body.user_id);
//Get user
newUserModel.findById(userId, function(err, user){
if(err){
utils.getResponse(res, req.url, messages.failure, "");
} else {
var userInfo = {};
var blcked_contacts;
//get users details from blocked contacts userid's array
newUserModel.find({'_id': {$in:user.blocked_contacts}}, function (err,blocked_users) {
if(blocked_users){
//blcked_contacts.push(blocked_users);
console.log(blocked_users);
return;
};
/*else{
blcked_contacts = [];
}*/
});
userInfo['blocked_contacts'].push(blocked_users);
userInfo['user_id'] = user.id;
userInfo['country_code'] = user.country_code;
//userInfo['blocked_contacts'].push(blcked_contacts);
//userInfo['blocked_contacts'] = user.blocked_contacts;
var userData = Array();
}
});
Don't really know what you're looking for. But saw a problem in your code. You've assigned the blocked_users to the blocked_contacts field outside the find method.
Since these calls are asynchronous in nature, it might happen that the assignment takes place even before the documents are fetched from MongoDB. So you should write your assignment statements inside the find methods' callback, just the way Medet did.
Noticed few mistakes in your code like trying to use .push on an object. You cant do
userInfo['blocked_contacts'].push(blocked_users); // incorrect as userInfo is an empty object and you dont have an array defined for userInfo['blocked_contacts']
You probably get cannot push into undefined error for this. So instead do
userInfo['blocked_contacts'] = blocked_users;
Also you have to do this inside the second find() as blocked_users is only available inside it. So your final query should be something like
var userId = ObjectID(req.body.user_id);
//Get user
newUserModel.findById(userId, function(err, user){
if(err){
utils.getResponse(res, req.url, messages.failure, "");
} else {
var userInfo = {};
//get users details from blocked contacts userid's array
newUserModel.find({'_id': {$in:user.blocked_contacts}}, function (err,blocked_users) {
if(blocked_users){
userInfo['user_id'] = user.id;
userInfo['country_code'] = user.country_code;
userInfo['blocked_contacts'] = blocked_users; // assign blocked_users into userInfo
console.log(userInfo) // Your required object
} else {
userInfo['user_id'] = user.id;
userInfo['country_code'] = user.country_code;
userInfo['blocked_contacts'] = []; // assign null array if no blocked users fould
}
});
var userData = Array();
}
});
The result of console.log should be an object like this
{
user_id : "..id of searched user...",
country_code : "..country code of searched user..",
blocked_contacts : [<array containing detais of all blocked users>] // null array if no users found
}

Categories