Retrieve id of model created in $afterInsert hook in Objection ORM - javascript

Is it possible to retrieve (at least) the id of created model in $afterInsert hook in Objection ORM?
async $afterInsert(queryContext)
I guess and hope it could be available somehow from queryContext?
The goal is to be able to log this id when created in an allowed graph through insertGraph method.

You can access the returned data at this:
async $afterInsert(queryContext) {
await super.$afterInsert(queryContext);
console.log(this.id)
}

Related

Sequelize create make more than one record issue

I'm trying to save logs on some events with sequelize create but when I call the create method more than one record saved (maybe 2 or 3 identical records).
I'm using node.js and sequelize.
I made sure that I called add method once and I await it.
controller:
async addLog(){
let log = await UserLog.addLog({Uid:user_id,date:new Date()})
return log
}
UserLog model:
public static async addLog(logObject: LogType) {
return await LogEntity.create(logObject, {raw: true});
}
any suggestions
Make sure addLog() function is getting called from one point only.
You can use upsert function of sequileze which inserts a new record only if a unique condition doesn't meet else it will updates the record. In your case Uid and date can be used for uniqueness.

Using firebase .update within a .where (instead of .doc)

I am new to firebase and am struggling a little bit.
Currently, I am trying to update an array within a user, within a document. However, I cannot match the user to current user using the unique ID, as each users unique ID is their username, and it may have changed since creation.
I figured the best way to match the documents user to the current user would be to use a .where().get() and then use an "update()" to update the array.
Now, this is where I am getting stuck. In the firebase documents, their example of using .update is attached to a .doc
var washingtonRef = db.collection("cities").doc("DC");
//Atomically add a new region to the "regions" array field.
washingtonRef.update({
regions: firebase.firestore.FieldValue.arrayUnion("greater_virginia")
});
However, as I am using a .where, I assume I have to use references and snapshots. But, I am not quite sure how references work in this scenario and, with that, how to update properly.
Here is the code I have after a while of messing round, but no matter my variations i cannot figure it out. (essentially, I want to add a new project (in this case called "new project" to the users array of postedProjects.)
db.collection('users').where('user_id', '==', this.userInfo.user_id)
.get()
.then(function(querySnapshot) {
querySnapshot.forEach(function(doc) {
doc.data().update({
postedProjects: firebase.firestore.FieldValue.arrayUnion("new project")
})
})
})
This gives me an error of ".update() is not a function".
Is anyone able to help me with my solution to show me how references should properly be used in this scenario?
You're almost there. You can't update the data of DocumentSnapshot though, since that is the in-memory representation of the document data. Instead you need to get the DocumentReference and call update on that.
doc.ref.update({
postedProjects: firebase.firestore.FieldValue.arrayUnion("new project")
})
You need a DocumentReference in order to update() a document. Nothing else will work.
In your code, doc is a QueryDocumentSnapshot type object. If you want the DocumentReference object that refers to the document from that snapshot, use its ref property.
doc.ref.update({
postedProjects: firebase.firestore.FieldValue.arrayUnion("new project")
})

Returning documents in Cloud Firestore

I'm absolutely new to Firestore and for some reason I can't get it right.
I'm trying to retrieve documents from it that I've just manually entered. Using node.js I make a call for a database snapshot like in the documentation:
db.collection('categories').get()
.then((docs) => {
res.json(docs)
})
But instead of an array of docs or something like this, I get this as a response:
_size is right, I have two documents in the collection - but I can't find them anywhere. What am I missing here?
Your docs variable is of type QuerySnapshot. Look at the methods available on that object. If you just want the raw documents out of it, use the docs property on it to get an array of QueryDocumentSnapshot objects. Each of those will have a method called data() on them to get the raw document data.

Get current user from inside the model in Sails

I'm using toJSON() method of my model in Sails in order to control the visibility of some of it's properties, when model is exposed via application's API.
In order to decide which properties to display and which to omit I need to know the permissions of the current user. So, how do I get the current user from inside the model? Or is there a better way (pattern) to solve this problem?
Here's some sample code I want to achieve:
toJSON: function () {
var result = {};
result.firstName = this.firstName;
result.lastName = this.lastName;
// Exposing emails only to admin users.
if (currentUser.isAdmin()) {
result.email = this.email;
}
return result;
}
Your asking about reading a session inside the model call. Currently the way sails and waterline are built you can not do this.
You can use the select property on your initial model call to restrict the columns returned. Since this would be in the context of your controller you would have access to the req object.
Here are a bunch of related questions / answers on this topic.
sails.js Use session param in model
Is it possible to access a session variable directly in a Model in SailsJS
https://github.com/balderdashy/waterline/issues/556
https://github.com/balderdashy/waterline/pull/787
Sails Google Group Discussion on the topic

EmberJS transitionTo firstObject for async hasMany

I want to redirect users to the route for the firstObject of a collection when they arrive at the containing object.
A container hasMany items, currently in the ContainerRoute.afterModel I am doing:
this.transitionTo('container.item.index', model, model.get('items').get('firstObject'));
Which is fine when the items are not async.
The problem is the firstObject isn't a promise so the route/transition doesn't pause.
Here is the model hook:
return this.get('store').find('container', params.containerId);
What's the cleanest approach? The options I see are:
change the model hook to populate the
build and pass a promise as the parameter to transitionTo
transitionTo the ID of the object instead of the object (writing a solution for this now)
transitionTo can take an object (actual or promise), or an ID.
I opted to just send the ID in the ContainerRoute:
this.transitionTo('container.item.index', model, model.get('firstItemId'));
You can get the ID without inflating the object by accessing:
this.get('data.submissions.firstObject.id');
Which was borrowed from a github issue about avoiding loadMany
The hasMany property is a promise like object, so you can use the then method, to know when it't is resolved:
model.get('items').then(function(items) {
this.transitionTo('container.item.index', model, items.get('firstObject'));
});

Categories

Resources