#Sequelize while adding retrieve all attributes - javascript

I would like to find a way to retrieve all my attributes while inserting in my Database.
models.association.build(associationParams)
.save()
.then(function(assoAdded){
return next(assoAdded);
}).catch(function(err){
// # TODO : implement error Handler
return next(err);
});
I got this :
{
"idAssoParente": null,
"id": 420,
"name": "a",
"email": "aa#aa.aa",
"updated_at": "2015-07-29T17:12:47.000Z",
"created_at": "2015-07-29T17:12:47.000Z"
}
But I want to return all my fields like description , phone , city from my database even if they are empty. Should I necessarily do a find after adding to get all my fields or does it exist a way to retrieve my fields without doing an other request ?
Thanks

In short, yes you would need to query your db to return the info. I just started using Sequelize but I found the following worked for me.
// if all the info you need is in your user
Users.build({req.body})
.save()
.then(function(newUser){
Users.find({where: {UserID: newUser.UserID}}).then(function(user){
//resolve your promise as you please.
});
// or if address info is in another model you can use eager loading.
Users.build({req.body})
.save()
.then(function(newUser){
Users.find({where: {UserID: newUser.UserID},
include: [{
model: address
}]
}).then(function(user){
//resolve your promise as you please.
});

Related

Remove element from Multiple MongoDB Array simultaneously

I am creating MERN Classroom where users can Create/Join classes using the class's unique Code. Whenever a user joins the classroom, class id gets pushed into the User's MongoDB document array (classesJoined) and the user id gets pushed into Classroom's MongoDB document array (classroomMembers)
Updated User's Document:
{
"_id": "62e7ef5f636d28247a21b1e7",
"name": "User One",
"email": "userone#mydomain.com",
"password": "encryptedPassword",
"classesJoined": [
"62e7f00e636d28247a21b20d",
"62e7f0a0636d28247a21b247"
]
}
Updated Classroom's Document:
{
"_id": "62e7f00e636d28247a21b20d",
"classroomName": "Class by User One",
"classroomCode": "9ljsgNqx",
"classroomMembers": [
"62e7ef5f636d28247a21b1e7"
]
}
When a user wants to leave the classroom, the classroom's ID should be removed from the User document as well as the User ID should also be removed from the Classroom Document.
To achieve this, I have tried this logic in my Express Server route:
try{
await Users.findByIdAndUpdate({_id: req.body.userID}, { $pull: { classesJoined: req.body.classID } })
await Classroom.findByIdAndUpdate({_id: req.body.classID}, { $pull: { classroomMembers: req.body.userID }
res.send("Class Removed")
})
} catch (error){
res.send("Error Occured")
}
POST Request Body Contains:
{
"userID": "62e7ef5f636d28247a21b1e7",
"classID": "62e7f00e636d28247a21b20d",
}
But the problem I am facing is that the User ID from Classroom.classroomMembers gets removed but in User Document, nothing is changing or showing an error. The classesJoined array keeps the same element.

MongoDB Get Field to Update a Value from Request Query

I have user object structured like this:
{
"id": "",
"username": "",
"name": "",
"bio": "",
"email": "",
"profileImg": "",
"phoneNumber": 0,
"messagingPoints": 0,
"funds": 0,
"inventoryId": "",
"lastLogin": "2022-02-23T03:27:13.535Z",
"isPrivate": false,
"messagesReceived": []
}
I want to be able to reach a patch endpoint to update any of these fields. For example, /api/user?id=userId&name=John, should be able to grab the field "name" and set it to John. /api/user/id=?id=userId&email=abc#gmail.com should grab the email field and set it to abc#gmail.com
I am struggling to find docs for MongoDB to accomplish this, so I'm wondering if it is not possible? Do I need a specific endpoint for each of these update operations (ex: /api/user/name?id=userId&value=John instead of /api/user?id=userId&name=John)?
If it is possible, how could I accomplish this? Thanks!
You can pass user ID in update filter. Also you can pass data in request body of the PUT request instead of query parameters.
app.put('/api/user', async (req, res) => {
const { id, ...data } = req.body;
// Filter out any invalid fields
// Update documents where id field is equal to value of id in request body
await collection.updateOne(
{ id },
{ $set: data }
);
return res.json({ data: "User updated" })
})

Optimalization of firebase query. Getting data by ids

I'm new in Firebase. I would like to create an app (using Angular and AngularFire library), which shows current price of some wares. I have list all available wares in Firebase Realtime Database in the following format:
"warehouse": {
"wares": {
"id1": {
"id": "id1",
"name": "name1",
"price": "0.99"
},
"id2": {
"id": "id2",
"name": "name2",
"price": "15.00"
},
... //much more stuff
}
}
I'm using ngrx with my app, so I think that I can load all wares to store as an object not list because normalizing state tree. I wanted load wares to store in this way:
this.db.object('warehouse/wares').valueChanges();
The problem is wares' price will be refresh every 5 minutes. The number og wares is huge (about 3000 items) so one response will be weight about 700kB. I know that I will exceed limit downloaded data in a short time, in this way.
I want limit the loading data to interesing for user, so every user will can choose wares. I will store this choices in following way:
"users": {
"user1": {
"id": "user1",
"wares": {
"id1": {
"order": 1
},
"id27": {
"order": 2
},
"id533": {
"order": 3
}
},
"waresIds": ["id1", "id27", "id533"]
}
}
And my question is:
Is there a way to getting wares based on waresIds' current user? I mean, does it exist way to get only wares, whose ids are in argument array? F.e.
"wares": {
"id1": {
"id": "id1",
"name": "name1",
"price": "0.99"
},
"id27": {
"id": "id27",
"name": "name27",
"price": "0.19"
},
"id533": {
"id": "id533",
"name": "name533",
"price": "1.19"
}
}
for query like:
this.db.object('warehouse/wares').contains(["id1", "id27", "id533"]).valueChanges();
I saw query limits in Angular Fire like equalTo and etc. but every is for list. I'm totally confused. Is there anyone who can help me? Maybe I'm making mistakes in the design of the app structure. If so, I am asking for clarification.
Because you are saving the ids inside user try this way.
wares: Observable<any[]>;
//inside ngOnInit or function
this.wares = this.db.list('users/currentUserId/wares').snapshotChanges().map(changes => {
return changes.map(c => {
const id = c.payload.key; //gets ids under users/wares/ids..
let wares=[];
//now get the wares
this.db.list('warehouse/wares', ref => ref.orderByChild('id').equalTo(id)).valueChanges().subscribe(res=>{
res.forEach(data=>{
wares.push(data);
})
});
return wares;
});
});
There are two things you can do. I don't believe Firebase allows you to query for multiple equals values at once. You can however loop over the array of "ids" and query for each one directly.
I am assuming you already queried for "waresIds" and you've stored those ID's in an array named idArray:
for id in idArray {
database.ref('warehouse/wares').orderByChild('id').equalTo(id).once('value').then((snapshot) => {
console.log(snapshot.val());
})
}
In order to use the above query efficiently you'll have to index your data on id.
Your second option would be to use .childChanged to get only the updated data after your initial fetch. This should cut down drastically on the amount of data you need to download.
Yes , you can get exactly data that you want in firebase,
See official Firebase documents about filtering
You need to get each waresID
var waresID = // logic to get waresID
var userId = // logic to get userId
var ref = firebase.database().ref("wares/" + userId).child(waresID);
ref.once("value")
.then(function(snapshot) {
console.log(snapshot.val());
});
this will return only data related to that waresID or userId
Note: this is javascript code, i hope this will work for you.

Error getting a single value from a collection

I have a collection called notification and i am trying to get a single value with findOne()
var allnotices = Notifications.findOne({eventownernumber:"2"},{sort: {noticedate: -1, limit: 1}}).noticemessage;
I want to get the value where the eventownernumber is 2 and i want to get the latest record and i only want one record.
Even though noticemessage is part of the row fields,i get the error that noticemessage is undefined.
This is the schema
{
"_id": "tmkWCydSKZtYdrKTZ",
"eventoriginalid": "3bXvARk6K6yhee6Hi",
"lat": "-1.851881824302658",
"lng": "96.987469482421875",
"eventownernumber": "1",
"eventownernames": "Test 1",
"eventtitle": "ci",
"eventtime": "08:05",
"invited": "0",
"eventduration": "21",
"eventtype": "notification",
"eventcategory": "hackathon",
"eventstatus": "11",
"createdAt": {
"$date": "2016-11-02T12:38:40.378Z"
},
"noticedate": {
"$date": "2016-11-02T16:50:53.394Z"
},
"noticenumber": "2",
"noticenames": "Test 2",
"noticemessage": "Test 2 has joined your event ci",
"noticestatus": "12"
}
Why is noticemessage undefined?.
There are four basic possibilities why Collection.findOne(query).key could yield an error:
There is no document matching the query therefore you're trying to reference undefined.key
The key in question doesn't exist in the returned document
The document exists in the database but isn't being published by the server and being subscribed to by the client
The document exists and is published and subscribed to but the subscription is not yet .ready(), i.e. you need to wait before you can access it.
A common defensive pattern is:
const oneDoc = myCollection.findOne(query);
let myVar = oneDoc && oneDoc.key;
if ( myVar ) {
// do the thing
} else {
// handle the error
}
You need to save the number as integer for eventownernnumber (and please write it like eventOwnerNumber, which is a good practice for readability), not string. Either use input type="number" or convert the value to integer like this:
Number(valueHere);
The rest of your query looks fine to me but you don't need limit since you do findOne() and you find the newest inserted doc with noticedate: -1
Another thing is, you need to save the date like this in your insert():
noticeDate: new Date() //your current query should give you the right document after this change

IBM worklight JSON store remove array of documents

I am working in IBM worklight hybrid app,i am using JSON store to store data,to remove records from collection,i am using id and i could able delete single record using id,how to delete multiple records together from JSON store,if any example is there it will be useful,can anyone help me in doing this?Thanks in advance.
Delete function:
var id = JSON.parse(localStorage.getItem('jsonindex'));
var query = {
_id: id
};
var options = {
push: true
};
try {
WL.JSONStore.get(PEOPLE_COLLECTION_NAME).remove(query, options)
.then(function (res) {
console.log("REMOVE_MSG");
})
.fail(function (errorObject) {
console.log("Not Removed");
});
} catch (e) {
alert(INIT_FIRST_MSG);
}
JSON data
[{
"_id": 16,
"json": {
"name": " Debit",
"cardmonth": " 8",
"cardyear": " 2028",
"number": " 4216170916239547"
}
}, {
"_id": 17,
"json": {
"name": " Credit",
"cardmonth": " 7",
"cardyear": " 2027",
"number": " 4216170916239547"
}
}]
Try:
WL.JSONStore.get('collectionName').remove([...], options);
Replace ... with {_id: 1}, {_id: 2} or whatever query you want to use to remove documents.
If it doesn't work, please upgrade to the latest version of Worklight and try again.
Relevant:
PI10959: JSONSTORE FAILS TO REMOVE ALL DOCS IN THE DOC ARRAY WHEN A DOC ARRAY IS PASSED
IBM Worklight JSONStore | Remove Document from Collection and erase it from memory
If you are able to delete the single record. its easy to delete multiple record. but it raises some performance issues you have so many records.
var id="3"; If you are deleting this one by using Delete method. just do it for multiple records
var ids=[];
when user selects item ids.push(item.id);
for(i=0;i<ids.length;i++){
Delete(ids[i]); //its your Delete method
}

Categories

Resources