I need to create an api to create an entity which must have a unique name in it's data.
exp:
{
name: "Reza",
...
}
The question is how to throw and error of that name is already taken.
I can handle it by reading the whole table and check if there is no object with that name and then create the entity, but what can I do with concurrency?
if someone else calls the create api in the same time and the same name it's not in db yet, then I can't notice it's a duplicate name, then we encounter a duplication.
The project is on a baas and the service uses a mongodb but i don't access it directly, and because of sharding I can't use unique indexing.
any workaround for this situations?
Try adding the already found names in the db in an array , and compare the name that is being inserted. I will post this code that checks wether the app name that is being inserted to the db if available and render it some where else , you can benefit from the concept.
const updateAppNames = async () => {
let apps = await purchaseFromAppObjectModel.find({}).sort({ name: 1 });
const availableApps = [];
for (var i = 0; i <= apps.length; i++) {
try {
const obj = apps[i];
const appName = obj.appName;
if (availableApps.includes(appName)) {
console.log("This app exists :", appName);
} else {
console.log("This app does not exist :", appName);
availableApps.push(appName);
console.log(availableApps);
}
} catch {
console.error();
}
}
return availableApps;
};
result :
This app does not exist : com.xxx
[ 'com.xxx' ]
This app does not exist : com.xxy
[ 'com.xxx', 'com.xxy' ]
This app exists : com.xxx
This app exists : com.xxx
This app does not exist : any game
[ 'com.xxx', 'com.xxy', 'any game' ]
This app exists : any game
This app exists : any game
This app exists : any game
This app exists : any game
This app does not exist : any.any.any
[
'com.xxx',
'com.xxy',
'any game',
'any.any.any'
]
This app exists : any.any.any
This app exists : any.any.any
This app exists : any.any.any
Related
I've searched and played around quite a bit and I've not come across the solution.
I am trying to manage subscription providers and preview features via the "azurerm_resource_provider_registration" resource.
i've got it working fine if I want to manage just one provider with multiple sub features using the following:
tfvars file
provider_name = "Microsoft.Network"
provider_feature_name = {
feature1 = {
feature_name = "BypassCnameCheckForCustomDomainDeletion"
registered = true
}
feature2 = {
feature_name = "AllowTcpPort25Out"
registered = true
}
}
main.tf
resource "azurerm_resource_provider_registration" "provider_registration" {
name = var.provider_name
dynamic "feature" {
for_each = var.provider_feature_name
content {
name = feature.value.feature_name
registered = feature.value.registered
}
}
}
works great if I only ever want to manage one provider and it's features.
The problem comes when/if I want to add an additional "provider_name". I've tried a separate provider_name block but I keep getting a "unexpected block here" error. if I introduce a block like so;
vars.tf
provider_name = {
provider1 = {
provider_name = "Microsoft.Network" {
feature1 = {
feature_name = "test"
registered = true
}
}
}
provider2 = {
provider_name = "Microsoft.Storage" {
feature2 = {
feature_name = "test2"
registered = true
}
}
}
}
main.tf
resource "azurerm_resource_provider_registration" "provider_registration" {
for_each = var.provider_name
name = each.value.provider_name
dynamic "feature" {
for_each = var.provider_feature_name
content {
name = feature.value.feature_name
registered = feature.value.registered
}
}
I can get it loop but cannot get it to associate only feature1 to provider 1 etc as these features are exclusive to that provider. It associates feature1 to provider 1 & 2.
If I try to introduce a for_each or dynamic group for the "name" value, it comes up with "blocks of type provider not expected here" and/or "argument name is required but no definition was found"
In short, how can I get my main to loop over each provider_name and only associate the sub block of features to that provider (with potential for multiple features per provider type). is it just not possible for this type of resource? or am I just not understanding the loop/for_each documentation correctly.
any help is appreciated
thank you.
First we need to cleanup and optimize the input structure. I have speculated on what the values should be since there are two different hypothetical structures specified in the question, but the structure itself is accurate.
providers = {
"Microsoft.Network" = {
features = { "BypassCnameCheckForCustomDomainDeletion" = true }
}
"Microsoft.Storage" = {
features = { "AllowTcpPort25Out" = true }
}
}
Now we can easily utilize this structure with a for_each meta-argument in the resource.
resource "azurerm_resource_provider_registration" "provider_registration" {
for_each = var.providers
name = each.key
dynamic "feature" {
for_each = each.value.features
content {
name = feature.key
registered = feature.value
}
}
}
and this results in two provider registrations with the corresponding feature mapped to each.
Just started using the Realm MongoDB and i watched this video https://www.youtube.com/watch?v=Evp3xTzWCu4 from MongoDB and followed exactly what he did, but for some the function on the client side is not working. I'm using Expo React Native
I have this simple Realm function
exports = function(arg){
var collection = context.services.get("mongodb-atlas").db("questiondb").collection("questions");
collection.insertOne({name:arg}).then((doc) => {
console.log('Success')
}).catch(error=>console.log(error))
};
When i call it in the real console, it works fine.
This is the front end function
const connectDB = async () => {
const appID = "myapp-ckwfl";
const app = new Realm.App({ id: appID });
const credentials = Realm.Credentials.anonymous();
try {
const user = await app.logIn(credentials);
await user.functions.addQuestion("Myself");
console.log("Logged in");
} catch (error) {
console.log(error);
}
};
I'm getting the 'Logged in' in the console.
I went to check the activity log on the MongoDB atlas and it shows OK to both login and function
However, the function log shows me this message
[ "FunctionError: can't find a table mapping for namespace questiondb.questions" ] { "name": "addQuestion" }
And i have the database 'questiondb' with the collection 'questions'.
What am i missing here?
I ran into a similar error. The problem was that my BSON did not contain an "_id" field. But the BSON validation when saving it allowed me to save the schema like that. But when querying data through graphql I got this exact same error. So the solution was to fix the BSON schema. Even if the BSON schema saves and deploys successfully it can still be that it will not work for graphql.
You can see if your BSON has errors by navigating here:
I got a schema looking something like this:
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
//Create Schema
const PhoneNumbersSchema = new Schema({
phone_numbers: {
phone_number: 072382838232
code: ""
used: false
},
});
module.exports = PhoneNumbers = mongoose.model(
"phonenumbers",
PhoneNumbersSchema
);
And then I got an end-point that gets called from a 3rd party application that looks like this:
let result = await PhoneNumbers.findOneAndUpdate(
{ country_name: phoneNumberCountry },
{ $set: {"phone_numbers.$[elem1].services.$[elem2].sms_code": 393} },
{ arrayFilters: [ { "elem1.phone_number": simNumberUsed }, { "elem2.service_name": "steam" } ] },
Basically the end-point updates the "code" from the phone numbers in the database.
In react this is how I retrieve my phone numbers from the state:
const phonenumbers_database = useSelector((state) => {
console.log(state);
return state.phonenumbers ? state.phonenumbers.phone_numbers_details : [];
});
Every time the code gets changed in my database from the API call I would like to update "phonenumbers_database" in my state automatically.
How would I be able to do that?
MongoDB can actually watch for changes to a collection or a DB by opening a Change Stream.
First, you would open up a WebSocket from your React app to the server using something like Socket.io, and then watch for changes on your model:
PhoneNumbers
.watch()
.on('change', data => socket.emit('phoneNumberUpdated', data));
Your third party app will make the changes to the database to your API, and then the changes will be automatically pushed back to the client.
You could do a polling and check the Database every N secs or by using change streams
After that, to notify your frontend app, you need to use WebSockets, check on Socket IO
I have an MongoDB Stitch app, that users the Email/Password authentication. This creates users within the Stitch App that I can authenticate on the page. I also have an MongoDB Atlas Cluster for my database. In the cluster I have a DB with the name of the project, then a collection underneath that for 'Matches'. So when I insert the 'Matches' into the collection, I can send the authenticated user id from Stitch, so that I have a way to query all Matches for a particular User. But how can I add additional values to the 'User' collection in stitch? That user section is sort of prepackaged in Stitch with whatever authentication type you choose (email/password). But for my app I want to be able to store something like a 'MatchesWon' or 'GamePreference' field on the 'User' collection.
Should I create a collection for 'Users' the same way I did for 'Matches' in my Cluster and just insert the user id that is supplied from Stitch and handle the fields in that collection? Seems like I would be duplicating the User data, but I'm not sure I understand another way to do it. Still learning, I appreciate any feedback/advice.
There isn't currently a way to store your own data on the internal user objects. Instead, you can use authentication triggers to manage users. The following snippet is taken from these docs.
exports = function(authEvent){
// Only run if this event is for a newly created user.
if (authEvent.operationType !== "CREATE") { return }
// Get the internal `user` document
const { user } = authEvent;
const users = context.services.get("mongodb-atlas")
.db("myApplication")
.collection("users");
const isLinkedUser = user.identities.length > 1;
if (isLinkedUser) {
const { identities } = user;
return users.updateOne(
{ id: user.id },
{ $set: { identities } }
)
} else {
return users.insertOne({ _id: user.id, ...user })
.catch(console.error)
}
};
MongoDB innovates at a very fast pace - and while in 2019 there wasn't a way to do this elegantly, now there is. You can now enable custom user data on MongoDB realm! (https://docs.mongodb.com/realm/users/enable-custom-user-data/)
https://docs.mongodb.com/realm/sdk/node/advanced/access-custom-user-data
const user = context.user;
user.custom_data.primaryLanguage == "English";
--
{
id: '5f1f216e82df4a7979f9da93',
type: 'normal',
custom_data: {
_id: '5f20d083a37057d55edbdd57',
userID: '5f1f216e82df4a7979f9da93',
primaryLanguage: 'English',
},
data: { email: 'test#test.com' },
identities: [
{ id: '5f1f216e82df4a7979f9da90', provider_type: 'local-userpass' }
]
}
--
const customUserData = await user.refreshCustomData()
console.log(customUserData);
I'm building an app with Firebase and AngularJS and I have a table with my users.
From one of my view I want to create a form permit to delete users from the Firebase table .
So I have a drop down menu with my users names and submit button.
I wrote a function to retrive the name of the user from the form and combine it with my url location of the user table, in fact the table has user name as id :
$scope.Delete_user = function(name) {
var testRef = new Firebase("https://alex-jpcreative.firebaseio.com/users")
var newRef = testRef + '/' + name;
$scope.removeUser(newRef);
}
In this function I called the removeUser one that is a function I found in Firebase doc to delete a item from the table :
$scope.removeUser = function(ref) {
ref.remove(function(error) {
alert(error ? "Uh oh!" : "Success!");
});
}
I can see the first function working fine pass the right name of users and combine it with the URL but then I have this error and it doesn't work:
TypeError: Object https://alex-jpcreative.firebaseio.com/users/Alex_dev_JPC has no method 'remove'
You need to use the child method to get the reference to the user object, rather than just appending the string to the end:
$scope.Delete_user = function(name) {
var testRef = new Firebase("https://alex-jpcreative.firebaseio.com/users");
var newRef = testRef.child(name);
$scope.removeUser(newRef);
}
See the Firebase documentation for more details.