get record `id` before create/save | Sails Js - javascript

I am trying to create a notification for user.
with notification url in description like this http://localhost:1337/invited/accept?referrer=msgIcon&id=this-notification-id the url has id of this newly created notification.
AppUserNotification.create({
projectId: projectId,
appuser: appusers.id,
notificationTitle: 'You are invited in project',
isRead: 0,
description: 'You are invited in project collaboration, '
+ 'please accept invitation by following the link.\nHave a good day !\n'
+ 'Accept Invitation http://localhost:1337/invited/accept?referrer=msgIcon&id=this-notification-id',
}).exec(function (err, appuserNotifications) {
apiStatus = 1; // heading toward success
if (err){
return false;
}else if(appuserNotifications){
return true;
}
});//</after AppUserNotification.create()>
what I want to do is to save a link in description with this newly created notification. but couldn't manage to do so.
please help me.

By default, id is generated by database during record creating. So can be accessed only after creation.
Here are some ways in which your objective can be achieved:
New attribute: Add another unique attribute which is used in description URL. It can be generated randomly before creation (e.g. can use UUID)
Use custom id: Set autoPK: false in Model, generate id yourself; (I have done it for MySQL in beforeCreate hook using UUID as primary key id, not sure about MongoDB)
Update after create: Use afterCreate hook to update description with id
New Model method: Define a method say getDescription() in the Model which returns something like this.description + this.id.
Override toJSON(): http://sailsjs.com/documentation/reference/waterline-orm/records/to-json

Related

Strapi query by unique field

I am getting started with Strapi and have setup a basic model in the Strapi admin called page which looks like so:
page: {
title: Text (required)
slug: Text (required and unique)
}
As you can see it has a field called slug which is always unique. What I am wondering is how I can query by this field?
So far I have added 1 entry and when I launch graphql playground (at http://localhost:1337/graphql) I can get my entry returned via the following query:
query {
page(id:"1") {
title
}
}
When I try to query via slug as opposed to id like so:
query {
page(slug:"/") {
title
}
}
I am unable to do so even though it's a unique field. It does not even come up with the suggestions to use slug as a unique idetifier input inside the brackets. Why would this be?

How to send non-persistent value to Cloud Firestore?

I want to send some value for a field to Cloud Firestore, but I dont want to be persist(saved) in Cloud Firestore.
Code:
const message = {
persistentData: {
id: 'dSXYdieiwoDUEUWOssd',
text: 'Hi dear how are you',
date: new Date();
},
nonPersistentData: {
securityCode: 393929949
}
};
db.collection('messages').doc(message.persistentData.id).set(message).catch(e => {});
In above code I want to persit (save) persistentData, but I dont want to save nonPersistentData online nor offline, because I only need them to check real data in Firestore rule. So I dont want they should be accessible in cache(offline) or server(online)...
This is simply not possible with firestore. There is a similar question here. You need to separate the data into public (persistent) and private data (non-persistent). One possible solution will be-
From the client, push the private data which contains the securityCode to a new collection called securityCodes and store the id of the new entry.
Because you don't want this info to be available to anyone, you can add a security rule
match /securityCodes/{securityCode} {
// No one can read the value from this collection, but only create
allow create: true;
}
In your public data, add the id of the previously added document
data = {
id: 'dSXYdieiwoDUEUWOssd',
text: 'Hi dear how are you',
date: new Date(),
securityId: <id of the secretCode entry>
}
In your security rules, get the secret code using the securityId you are sending with the public data. Example-
match /collectionId/documentId {
allow create: if get(/secretCodes/$(request.resource.data.secretId)) == 'someknowncode'
}

Accessing Other Entities Attributes in Dynamics CRM/365 Forms with javaScript

This function buttonBuzz() works inside the Forms of the Entities Account, Contacts and Leads. But not in the Opportunity form.
Mainly because there is no telephone1 attribute. There is however a Contact entity added with "Quick View" in a section with a telephonenumber inside.
I think it can be accessed with the telephone1 as well just not with Xrm.page
Any ideas how i can grab the attribute from inside the "quick view"?
I dont know if the "Quick view" window is a form of an iFrame. And if it is i have no clue how to access it with the Xrm.Page.getAttribute("telephone1").getValue();
function buttonBuzz(exObj) {
var phoneNumber;
// Here i store the "telephone1" Attribute from the current .page
phoneNumber = Xrm.Page.getAttribute("telephone1").getValue();
if (phoneNumber != null) { **Sends phonenumber** } ...
Quick Views display data from a record selected in a lookup field, in this case a Contact. You can query data from related records using the OData endpoint.
You first need to get the Guid of the record selected:
var contactId = Xrm.Page.getAttribute("parentcontactid")[0].id || null;
You would then need to send a SDK.REST request, passing parameters for the Id of the record (contactId), entityName and the columns:
var entityName = "Contact";
var columns = "Address1_Telephone1, FirstName, LastName";
SDK.REST.retrieveRecord(contactId, entityName, columns, null, function(result) {
// Success, logic goes here.
var address1_Telephone1 = result.Address1_Telephone1;
}, function(e) {
console.error(e.message);
});
As well as your JavaScript file, you would need to include the SDK.REST.js file that is included in the MS CRM SDK download within your Opportunity form libraries.
You can pull that field up from the Contact into the Opportunity by creating a Calculated Field, setting it equal to parentcontactid.telephone1
Put the field on the form, and you'll be able to .getAttribute() it like any other Opportunity field (being Calculated, it updates itself whenever the source changes).

Create RethinkDB table on first getRecord in deepstream.io

I have a deepstream server connected to RethinkDB with the official connector.
server.set( 'storage', new RethinkDbConnector({
port: 28015,
host: rethinkDbHost,
splitChar: '/',
defaultTable: 'ds-records'
}));
There are no tables in the database at first.
When I create a record, a table is created automatically if it does not exist.
var id = "chat/" + ds.getUid();
var record = ds.record.getRecord(id);
record.whenReady(function() {
record.set({user: data.user, message: data.message, timestamp: Date.now(), id: id});
});
Table created as intended.
However, if I try to create a "nested table", it does not work.
var id = "chat/idle_banter/" + ds.getUid();
var record = ds.record.getRecord(id);
record.whenReady(function() {
record.set({user: data.user, message: data.message, timestamp: Date.now(), id: id});
});
No table is created when trying to create a record with the name 'table/collection/id'
Do I have to create a table manually first, and then add the collection?
Edit
Clumsy use of terms on my part. I wish to create a table representing the entire chat, and then create a document that represents the actual room. New chat messages (records) would then be put in this document.
I have to admit that I don't think that RethinkDB supports a concept of nested tables. If you'd like to create a table per chat, just use a character other than the splitChar, e.g. 'chat-idle_banter/<recordName>'

Mongo check if a document already exists

In the MEAN app I'm currently building, the client-side makes a $http POST request to my API with a JSON array of soundcloud track data specific to that user. What I now want to achieve is for those tracks to be saved to my app database under a 'tracks' table. That way I'm then able to load tracks for that user from the database and also have the ability to create unique client URLs (/tracks/:track)
Some example data:
{
artist: "Nicole Moudaber"
artwork: "https://i1.sndcdn.com/artworks-000087731284-gevxfm-large.jpg?e76cf77"
source: "soundcloud"
stream: "https://api.soundcloud.com/tracks/162626499/stream.mp3?client_id=7d7e31b7e9ae5dc73586fcd143574550"
title: "In The MOOD - Episode 14"
}
This data is then passed to the API like so:
app.post('/tracks/add/new', function (req, res) {
var newTrack;
for (var i = 0; i < req.body.length; i++) {
newTrack = new tracksTable({
for_user: req.user._id,
title: req.body[i].title,
artist: req.body[i].artist,
artwork: req.body[i].artwork,
source: req.body[i].source,
stream: req.body[i].stream
});
tracksTable.find({'for_user': req.user._id, stream: req.body[i].stream}, function (err, trackTableData) {
if (err)
console.log('MongoDB Error: ' + err);
// stuck here - read below
});
}
});
The point at which I'm stuck, as marked above is this: I need to check if that track already exists in the database for that user, if it doesn't then save it. Then, once the loop has finished and all tracks have either been saved or ignored, a 200 response needs to be sent back to my client.
I've tried several methods so far and nothing seems to work, I've really hit a wall and so help/advice on this would be greatly appreciated.
Create a compound index and make it unique.
Using the index mentioned above will ensure that there are no documents which have the same for_user and stream.
trackSchema.ensureIndex( {for_user:1, stream:1}, {unique, true} )
Now use the mongoDB batch operation to insert multiple documents.
//docs is the array of tracks you are going to insert.
trackTable.collection.insert(docs, options, function(err,savedDocs){
//savedDocs is the array of docs saved.
//By checking savedDocs you can see how many tracks were actually inserted
})
Make sure to validate your objects as by using .collection we are bypassing mongoose.
Make a unique _id based on user and track. In mongo you can pass in the _id that you want to use.
Example {_id : "NicoleMoudaber InTheMOODEpisode14",
artist: "Nicole Moudaber"
artwork: "https://i1.sndcdn.com/artworks-000087731284-gevxfm-large.jpg?e76cf77"
source: "soundcloud"
stream: "https://api.soundcloud.com/tracks/162626499/stream.mp3? client_id=7d7e31b7e9ae5dc73586fcd143574550"
title: "In The MOOD - Episode 14"}
_id must be unique and won't let you insert another document with the same _id. You could also use this to find the record later db.collection.find({_id : NicoleMoudaber InTheMOODEpisode14})
or you could find all tracks for db.collection.find({_id : /^NicoleMoudaber/}) and it will still use the index.
There is another method to this that I can explain if you dont' like this one.
Both options will work in a sharded environment as well as a single replica set. "Unique" indexes do not work in a sharded environment.
Soundcloud API provides a track id, just use it.
then before inserting datas you make a
tracks.find({id_soundcloud : 25645456}).exec(function(err,track){
if(track.length){ console.log("do nothing")}else {//insert}
});

Categories

Resources