To clarify, I'm trying to build a feature to let my users manage the notifications and emails they receive.
In order to do that, I decided to implement an object with several objects within itself.
Everything seems to make sense in my head but I'm here because I found a problem and I can not solve it by myself.
Here is the problem:
I have two endpoints and two function, each endpoint calls their respective function. Everytime I make a call to any of the two endpoints, said call updates not only the data on its endpoint but in the other endpoint as well, do I explain myself?
Let's put it this way, this is endpoint A {{URL}}/api/v1/auth/updateemailnotifications and this ednpoint B {{URL}}/api/v1/auth/updatenotifications. No matter which one is called, it updates the other's endpoint data as well.
ENDPOINT A:
const user = await User.findByIdAndUpdate(
{
_id: req.user._id
},
{
$set: {
settings: {
notifications: {
comments: {
fromBlogNotification: req.body.fromBlogNotification,
fromPostNotification: req.body.fromPostNotification,
fromVideoNotification: req.body.fromVideoNotification,
fromMediaNotification: req.body.fromMediaNotification,
fromProducerNotification: req.body.fromProducerNotification,
fromJobNotification: req.body.fromJobNotification,
fromCommentNotification: req.body.fromCommentNotification
},
news: {
fromBlogNewsNotification: req.body.fromBlogNewsNotification,
fromProducerNewsNotification:
req.body.fromProducerNewsNotification,
fromUserNewsNotification: req.body.fromUserNewsNotification
}
}
}
}
},
{
new: true,
runValidators: true,
// setDefaultsOnInsert: true
}
);
ENDPOINT B:
const user = await User.findByIdAndUpdate(
{
_id: req.user._id
},
{
$set: {
settings: {
emails: {
comments: {
fromBlogComments: req.body.fromBlogComments,
fromPostComments: req.body.fromPostComments,
fromVideoComments: req.body.fromVideoComments,
fromMediaComments: req.body.fromMediaComments,
fromProducerComments: req.body.fromProducerComments,
fromJobComments: req.body.fromJobComments,
fromCommentComments: req.body.fromCommentComments
}
}
}
}
},
{
new: true,
runValidators: true,
// setDefaultsOnInsert: true
}
);
Hopefully you guys can help me solve this, thanks!.
In your code, you are replacing the whole settings with the new value. To update specific field in settings, you need to use dot notation:
const user = await User.findByIdAndUpdate(
{ _id: req.user._id },
{
$set: {
'settings.notifications': {
...
}
}
},...
Related
I am using prisma with mongoDb for the first time and I want to update a boolean value stored in a collection, but I am not able to find a way/query to update the value from true to false or vise versa...:(
const updateUser = await prisma.user.update({
where: {
userToken: token,
},
data: {
isOnline: true,
},
})
I have this 'isOnline' stored as false default and this is what I have tried wrt prisma official documentation, but this did not worked for me
I think you are looking for set
const updateUser = await prisma.user.update({
where: {
userToken: token,
},
data: {
isOnline: {
set: true
},
},
})
Since true and false values could be mistaken as a special instruction in "prisma logics", the response from #Fastnligth should be the correct one -did't tried that though-.
Since Prisma ORM implemented MongoDB as an after thought, some of these functionalities might "seem a bit off".
I've arrived here trying to update an embedded field without updating the whole document, just the given field.
Leaving my two cents in case somebody else is having the same sailing over google ⛵️
You can do that as follows
const order = await prisma.order.update({
where: {
id: 'some-object-id',
},
data: {
shippingAddress: {
// Update just the zip field
update: {
zip: '41232',
},
},
},
})
official docs: https://www.prisma.io/docs/concepts/components/prisma-client/composite-types
I have a Node.js application in which I am trying to remove an object from an array when an API endpoint is hit. I so far have been unable to get it to update/remove the object. Currently, the below query returns with no error but upon checking into my DB I am still seeing it. Below is my query and basic response (I will be adding more but that is outside the scope of this question). I have also included a sample of my data model.
In the below data model I am trying to remove the whole object from the foo array as it is no longer needed.
Code
const ID = req.params.id
await FooBar.updateOne({foo: {$elemMatch: {v_code: ID}}}, { $pull: {v_code: ID}}, (err) => {
if(err) return res.json({success: false, err})
return res.json({success: true, id: ID})
})
Data model
{
bar: [
{
foo: [
{
v_code: <>
_id: <>
}
]
}
]
}
I'm sure this has been asked for in other questions but none specific to my data model. I've tried piecing together multiple SO posts and that is how I got the $elemmatch and the $pull portions of my query and so far I've had zero luck
give the following command a try:
db.collection.updateOne(
{
"bar.foo.v_code": ID
},
{
$pull: { bar: { foo: { $elemMatch: { v_code: ID } } } }
}
)
https://mongoplayground.net/p/iqJki-mnHSJ
I am having some issues performing a nested find query with TypeORM. Here's the basic code:
const { completionId } = req?.params;
const user = req.user;
const retrievedCompletion = await getRepository(
CompletionGoogleSearch
).findOne({
relations: ['run', 'run.user'],
where: {
id: completionId,
// run: { user: { id: user.id } }, // This is the code that breaks the function
},
});
console.log(retrievedCompletion?.run.user.id);
console.log(user.id);
It looks to me like there's nothing out of order, and that the query should run. Any idea on what I am doing wrong? I know I can get around this issue by writing a querybuilder query or using raw SQL–I am just curious to understand if there's a flaw in my code.
typeorm added the ability to use nested object
userRepository.find({
relations: {
profile: true,
photos: true,
videos: {
videoAttributes: true,
},
},
});
on this way, you can fetch the data without using eager.
You can find more information here
The feature you're asking about doesn't supported on typeorm yet (Feb 2021).
Checkout this issue that was opened on 2018.
the Solution is use eager:true in run.user entity :
#OneToOne(() => User, User=> User.run, {
eager:true
})
user: User;
and next time you search in CompletionGoogleSearch do just relations: ['run'] and user will come with it.
I am working on meteor js, there will be huge data in mongodb database. For now it is around 50000 messages in database. I am providing the code that I am currently using. For some reason the application is taking too much time to render or load the data from database. Also one more thing, if I am doing any activity,e.g. just like the messages the app fetches the messages again from database.
Template.messages.helper({
linkMessages() {
var ids = _.pluck(Meteor.user().subscription, '_id');
var messages = Messages.find({ $or: [{ feedId: { $exists: false }, link: { $exists: true } }, { feedId: { $in: ids }, link: { $exists: true } }] }, { sort: { timestamp: 1 }, limit: Session.get("linkMessageLimit") }).fetch();
return messages;
}
})
calling publication in oncreate method
Template.roomView.onCreated(function() {
const self = this;
Deps.autorun(function() {
Meteor.subscribe('messages', Session.get('currentRoom'), Session.get('textMessageLimit'), {
onReady() {
isReady.messages = true;
if (scroll.needScroll) {
scroll.needScroll = false;
if (scroll.previousMessage) {
Client.scrollToMessageText(scroll.previousMessage);
}
} else {
Meteor.setTimeout(function() {
Client.scrollChatToBottomMsg();
}, 1000)
}
}
});
});
});`
The publication function on server:
Meteor.publish('messages', function(roomId, limit) {
check(roomId, String);
check(limit, Match.Integer);
let query = { $or: [{ link: {$exists: false} }, { feedId: { $exists: false } }] };
const thresholdMessage = Messages.findOne(query, { skip: limit, sort: { timestamp: 1 } });
if (thresholdMessage && thresholdMessage.timestamp) {
query.timestamp = { $gt: thresholdMessage.timestamp };
}
return Messages.find(query, { sort: { timestamp: -1 } });
});
It is not a good practice to allow mini-mongodb to get populated with such a huge data. Though Meteor JS is good at this too, still it will take some amount of time taking into consideration the network traffic, bandwidth etc.
Irrespective of whether it is unlimited scroll or simple pagination I would suggest you to use pagination. I have already got it accepted and it works like charm, here is the answer and entire code for pagination.
My pagination solution is server specific, so it performs good. Collection publish is limited to the limit provided from subscription.
NOTE: There is yet no such proper full fledged solution for table with search and pagination and much more facility which makes it very flexible as per our need. I suggest to create your own.
MORE INSIGHTS:
https://www.quora.com/Does-Meteor-work-well-with-large-datasets
https://forums.meteor.com/t/very-big-data-collection-in-mongodb-how-to-fetch-in-meteor-js/6571/7
https://projectricochet.com/blog/top-10-meteor-performance-problems
I want to implement a follow system between users.
For that, I want to display all of the 250 users of my app, then add a checkmark button next to the ones I already follow, and an empty button next to the ones I do not follow.
var usersRef = firebase.database().ref(‘/users’);
var followingRef = firebase.database().ref(‘/followingByUser’);
var displayedUsers = [];
// I loop through all users of my app
usersRef.once('value', users => {
users.forEach(user => {
// For each user, I check if I already follow him or not
followingRef.child(myUid).child(user.key).once('value', follow => {
if (follow.val()) {
// I do follow this user, follow button is on
displayedUsers.push({
name: user.val().name,
following: true
});
} else {
// I do not follow this user, follow button is off
displayedUsers.push({
name: user.val().name,
following: false
});
}
})
})
})
When doing that, I often (not always) get the following error: "Error: Firebase Database (4.1.3) INTERNAL ASSERT FAILED: sendRequest call when we're not connected not allowed."
Eventually, all the data is fetched, but after 10 seconds instead of 1 (without the error).
I do not believe it is an internet connection issue, as I have a very fast and stable wifi.
Is it a bad practice to nest queries like that?
If not, why do I get this error?
My data is structured as below:
users: {
userId1: {
name: User 1,
email: email#exemple.com,
avatar: url.com
},
userId2: {
name: User 2,
email: email#exemple.com,
avatar: url.com
},
...
}
followByUser: {
userId1: {
userId2: true,
userId10: true,
userId223: true
},
userId2: {
userId23: true,
userId100: true,
userId203: true
},
...
}
Your current database structure allows you to efficiently look up who each user is following. As you've found out it does not allow you to look who a user is follow by. If you also want to allow an efficient lookup of the latter, you should add additional data to your model:
followedByUser: {
userId2: {
userId1: true,
}
userId10: {
userId1: true,
},
userId223: {
userId1: true,
},
...
}
This is a quite common pattern in Firebase and other NoSQL databases: you often expand your data model to allow the use-cases that your app needs.
Also see my explanation on modeling many-to-many relations and the AskFirebase video on the same topic.