save object Id from one table to another table - string

I am getting ObjectId from one table and want to save another table which has column field name 'owner' with datatype 'Pointer<_User>'. But when I tried to do this I got this error 'invalid type for key owner, expected *_User, but got string'.
Please help me out. Thanks.

The problem lies in the title of the question. The operand to a pointer column isn't an object id, it is an object.
So if you have an object, say a PFUser, do this:
// user is a PFUser
myObjectThatPointsToUser("owner", user);
If you have only a user's object id as a string, ask yourself why. To the extent you can, design to converse in objects, not ids. But if you find yourself in this situation, set the pointer column like this:
// userId is the id of a PFUser
var userStub = { "__type": "Pointer",
"className": "_User",
"objectId": userId };
myObjectThatPointsToUser("owner", userStub);

Related

Proper Sequelize flow to avoid duplicate rows?

I am using Sequelize in my node js server. I am ending up with validation errors because my code tries to write the record twice instead of creating it once and then updating it since it's already in DB (Postgresql).
This is the flow I use when the request runs:
const latitude = req.body.latitude;
var metrics = await models.user_car_metrics.findOne({ where: { user_id: userId, car_id: carId } })
if (metrics) {
metrics.latitude = latitude;
.....
} else {
metrics = models.user_car_metrics.build({
user_id: userId,
car_id: carId,
latitude: latitude
....
});
}
var savedMetrics = await metrics();
return res.status(201).json(savedMetrics);
At times, if the client calls the endpoint very fast twice or more the endpoint above tries to save two new rows in user_car_metrics, with the same user_id and car_id, both FK on tables user and car.
I have a constraint:
ALTER TABLE user_car_metrics DROP CONSTRAINT IF EXISTS user_id_car_id_unique, ADD CONSTRAINT user_id_car_id_unique UNIQUE (car_id, user_id);
Point is, there can only be one entry for a given user_id and car_id pair.
Because of that, I started seeing validation issues and after looking into it and adding logs I realize the code above adds duplicates in the table (without the constraint). If the constraint is there, I get validation errors when the code above tries to insert the duplicate record.
Question is, how do I avoid this problem? How do I structure the code so that it won't try to create duplicate records. Is there a way to serialize this?
If you have a unique constraint then you can use upsert to either insert or update the record depending on whether you have a record with the same primary key value or column values that are in the unique constraint.
await models.user_car_metrics.upsert({
user_id: userId,
car_id: carId,
latitude: latitude
....
})
See upsert
PostgreSQL - Implemented with ON CONFLICT DO UPDATE. If update data contains PK field, then PK is selected as the default conflict key. Otherwise, first unique constraint/index will be selected, which can satisfy conflict key requirements.

Dynamodb putItem written twice

I am new to AWS and I feel like I am missing something important.
I am using this code from a lambda function in nodeJS to create an entry in a DynamoDB table :
function recordUser(item) {
return ddb.putItem({
TableName: 'Users',
Item: item,
Expected: {
username: { Exists: false }
}
}).promise();
}
username is the primary key of my table.
I though the condition would restrain duplicates to appear but I still see some duplicated entries with same username, what am I missing ?
You are giving "Expected" a wrong interpretation... You seemed to hope that it checks whether there is any existing item in the database with the given value for the "username" attribute. But this is not what Expected does... It does something very different: It reads one specific item - the item with the same key as the one you specified in "Item", and then check whether for this specific item, a value (any value!) exists for its "username" attribute.
To suggest how to fix your use case, we would need to know more about your data. The easiest solution is, of course, to have a table whose sole key is "username", which will allow just one item per username. But I don't know if this is good enough for your usecase.

Not able to access the data inside of an object

I am fetching id column value from database for a particular email. In this case I am passing email and want to get primary key i.e id. This operation is successful as I get object which contains Object with the right and expected result. However I am not able to access the object.
I am receiving object like this:
[ UserInfo { id: 21 } ]
And I am not able to access id part of it.
I am using node.js, postgres for database and typeorm library to connect with database.
const id = await userRepo.find({
select:["id"],
where: {
email:email
}
});
console.log(id)
This prints the above object.
The id I am getting is right. But I am not able to retrieve the id part of the object. I tried various ways for e.g.
id['UserInfo'].id, id.UserInfo.
Please help me in accessing the object I am receiving
Typeorm .find() returns an array of objects containing entries corresponding to your filters, in your case, all entries with an email field corresponding to the email you specified.
Because the result is an array, you can access it this way:
const records = await userRepo.find({
select: ['id'],
where: {
email,
},
})
console.log(records[0].id)
You could also use the .findOne() method, which returns a single element and might be a better solution in your case :)
When you are putting a field in the select part select:["id"], you are only retrieving this part of the database.
It is like your query was this: select id from userRepo where email = email
and you need to put * in the select part to retrieve all the information:
const id = await userRepo.find({
select:["*"],
where: {
email:email
}
});

CastError: Cast to string failed for value

I wanted to created a transaction module where after a successful transaction the users document(in this case user sends money to another user) will be updated as well.
a. in user.js(this is user model) besides name, pw, email (etc) I created this property which will hold the transaction related history of respective user. Please look at how I’ve used it:
transaction_history:[{
transactionid:String,
timestamp:String,
type:String,
balance:Number,
status:String
}]
b. when sender clicks send button in the form, a transaction document is created, & after this the user document(here the sender) should be updated along with transaction info.
//create transaction document, works fine
Transaction.create({transactionid:uniqid(),
timestamp:moment().format(datemask),
amount:balance,
sender:sendfrom,
receiver:sendto,
status:"done"
}, function(err, tr){
if(err) throw err;
else {
//I want sender document to update with transaction info
User.findOne({email:sendfrom}, function(err, sendfrom){
if(err) {console.log("error at sender side");}
else
if(sendfrom!=null){
// console.log("tr: "+tr); //fine
sendfrom.balance-=balance;
sendfrom.transaction_history.push({
transactionid:tr.transactionid,
// timestamp:tr.timestamp,
// type:"debit",
// balance:tr.amount,
// status:tr.status
}
);
sendfrom.save();
console.log("sender's current balance is: "+sendfrom.balance);
};
});
}});
c. But then I get this:
events.js:163
throw er; // Unhandled 'error' event
^
CastError: Cast to string failed for value "{ transactionid: '1amhrummxjhnhv0w4' }" at path "transaction_history"
Why this error occurs?I want your suggestion please! Thank you
You can't use the word 'type' as an object. Just rename to something else like 'something_type'.
Root of the problem is in the way I defined transaction_history property. This was supposed to be an array of objects syntactically[{}], but then I wrote its type to be String. So when I tried to insert a string as a value of ’type’, it throws error being unable to push string to ‘transaction_history’ object. To solve it, just need to remove type property. It’s my mistake to use a reserved word as a key in object.So I replaced 'type' by something else in model. that’s it!
At my case:
CastError: Cast to String failed for value "[ 'whateverValue_1', 'whateverValue_2' ]" at path "name"
Issue was that I have in form html name same word...
I.e:
<input name = "name"> Name
<input city = "name"> City
Looking for my mistake, I leave you other that could help for newbies as me:
words like type, model, never have to be in model Schema as main keywords!
There is a workaround provided by Mongoose:
You can use the field "type" in the object as long as you define its type, as such:
transaction_history: [
{
transactionId: String,
timestamp: String,
type: { type: String },
balance: Number,
status: String
}
]
source: https://www.typeerror.org/docs/mongoose/schematypes

Saving a Person or Group field using REST

Does anyone know how to save a Person field using REST?
I have tried the following and it works:
{
"__metadata": { "type": "SP.Data.SomeListListItem" } ,
"MyPersonFieldId" : 1
}
But this only works if you know the ID. I don't have that! How can I get it? I have the key which is i.0#w|domain\userName.
I tried the following and it doesnt work either:
{
"__metadata": { "type": "SP.Data.SomeListListItem" } ,
"MyPersonField" : { "__metadata": { "type": "SP.Data.UserInfoItem" }, "Name": "i.0#w|domain\userName" }
}
Any ideas?? Thanks!
I haven't done this with a Person field, but I did do something similar with a managed metadata field. I basically had to pass in additional information as an object to create the value in the field.
See if passing in the ID of the user along with the name works. I'm about to try this myself as I have the same need.
{
"MyPersonField": { "Name": "i.0#w|domain\userName", "ID": 1 }
}
EDIT: Ok, updating this field is easier than I thought. I was able to perform the update by simply passing in the ID of the user to the Id field:
{
"MyPersonFieldId": 1
}
This means the user should already be in the site collection, so if the user doesn't exist the request will fail.
Use the below code to get Current User ID to save user under People and group column. People column name is Requestor. But to save user we have to specify column name as RequestorId
var userid = _spPageContextInfo.userId; // To get current user ID
var itemProperties={'Title':vTitle,'RequestorId':userid};
The thing is that User information is a lookup field thereby MyPersonField does not exist on your SharePoint list if you use an OData endpoint, I really don't know how to save data but same problem happened to me when I tried to read a user.
for example {server}/{api}/list/getbytitle('mylist')/items does not return MyPersonField instead return MyPersonFieldId.
But if we use:
{server}/{api}/list/getbytitle('mylist')/items/?$select=*,MyPersonField/Name&$expand=MyPersonField
We are able to work with MyPersonField lookup values.

Resources