Creating Object array using lodash - lodash

I want to create an object array from a user collection. Following is the linq query in C#. I want help in creating the collection using lodash
var result = from user in Users
select new
{
Name = user.Name,
UserId= user.Id
};
return result;

solved it using _.map
_.map(Users, function (user, index) {
return { Name: user.Name, UserId: user.Id }; });

Related

TypeORM select data from nested relations

Using
await this.budgetRepository.createQueryBuilder("budget")
.leftJoinAndSelect("budget.contact", "contact")
.leftJoinAndSelect("contact.photo", "contactPhoto")
.getMany();
I get a list with objects like this:
Budget {
id: 1,
unnecessary_property1: something,
contact: Contact {
unnecessary_property2: something,
photo: Photo {
unnecessary_property3: something,
url: "url.com"
},
},
}
But I want to select only the necessary properties in the nested objects (relations) and get a list of objects like this:
Budget {
id: 1,
contact: Contact {
photo: Photo {
url: "url.com"
},
},
}
How is that possible with TypeORM?
This is possible but we have to select everything manually with .select()
await this.budgetRepository.createQueryBuilder("budget")
.leftJoinAndSelect("budget.contact", "contact")
.leftJoinAndSelect("contact.photo", "contactPhoto")
.select(['budget.id', 'contactPhoto.url']
.getMany();
If you're using repository pattern that you will be achieve the similar result with:
await this.budgetRepository.find({
relations: ["contact", "contact.photo"]
})
You would have to use the .select() function and pass the given properties you want for each entity.
for your example:
const user = await createQueryBuilder("budget")
.leftJoinAndSelect("budget.contact", "contact")
.leftJoinAndSelect("contact.photo", "contactPhoto")
.select([/* everything from budget */, 'contact.photo.url'....]) // added selection
.getMany();

Why is my SQL data returning undefined in my array methods?

The First array returned when I console log person
The second array that returns when I console log person
I am trying to create a function that pulls the data from 2 tables in my SQL database. I am using async/await, which is still new to me. The issue is somewhere in the two array methods; for some reason they are returning data as undefined.
async function updateRole() {
console.log('hi');
//cycle through both arrays and create new arrays with same information using maps
//return object with employee and role info
const allEmployees = await db.promise().query(`SELECT * FROM employees`);
const allRoles = await db.promise().query(`SELECT * FROM roles`);
console.log(allEmployees);
const employeeChoices = allEmployees.map((person) => {
return {
name: `${person.first_name} ${person.last_name}`,
value: person.id
}
})
const roleChoices = allRoles.map((role) => {
return {
name: role.title,
value: role.id
}
})
const { employeeId, roleId } = await inquirer.prompt([
{
type: 'list',
name: 'employeeId',
message: 'Which employee would you like to update?',
choices: employeeChoices
},
{
type: 'list',
name: 'roleId',
message: 'What is their new role?',
choices: roleChoices
}])
await db.promise().query(`UPDATE employees SET role_id = ? WHERE id = ?`, [roleId, employeeId])
console.log('Successfully updated employee!');
askQuestions();
Update: I added screenshots fo the console log for person. role returns the same format, but obviously different data. I am unsure what the array of ColumnDefinition objects does, or why it's there.

How to save object in mongoose

I want to use object to combine admins, but I cant figure out. Here is the schema and code
UserSchema = new mongoose.Schema({
name: { type:String },
owner : {
Admin : mongoose.Schema.Types.ObjectId
}
});
And saving function:
user.name = 'nerkn';
user.owner={ Admin :new ObjectId(Adminid)} // this is from another user
el = req.db.model('Users')(user)
el.save((err)=>{console.log(err)})
console.log('el', el)
when I check name is saved but owner.Admin is not.
You should mark as modified nested objects before save
el.markModified('owner');

Query User by ID QuickBlox

I'm building an app using the QuickBlox SDK. I have the user's ID stored and need to use that ID to retrieve the user object. Essentially I need to query for the user by ID and retrieve the user object How is this possible?
I attempted to use the userWithID method but it seems this has been deprecated. Any advice would be appreciated.
As per QuickBlox officail doc , the method you find is deprecated but you can use this below method to get user(s) by user(s) id
official doc of QuickBlox for android
QBPagedRequestBuilder pagedRequestBuilder = new QBPagedRequestBuilder();
pagedRequestBuilder.setPage(1);
pagedRequestBuilder.setPerPage(50);
ArrayList<Integer> usersIds = new ArrayList<>();
usersIds.add(qbChatDialog.getRecipientId());//set user id(s) here
QBUsers.getUsersByIDs(usersIds, pagedRequestBuilder).performAsync(new QBEntityCallback<ArrayList<QBUser>>() {
#Override
public void onSuccess(ArrayList<QBUser> users, Bundle params) {
//here you can get User(S) detail in users arrayList
String email = users.get(0).getEmail();
}
#Override
public void onError(QBResponseException errors) {
Log.e("error" , errors.toString());
}
});
You can use QB.users.listUsers to retrieve the user object from userid. I had attached source code here.It's work for me
var userId = 18767586;
var params = {
filter: { field: 'id', param: 'in', value: [userId] },
order: { sort: 'desc', field: 'id' }
};
QB.users.listUsers(params, function(err, result){
if (err) {
console.log("errMsg ==> ", err);
} else {
_.each(result.items, function(item) {
console.log("User Object ", item.user);
console.log(item.user.full_name);
// here you can get the user
});
}
});
This solution has been found from http://qaoverflow.com/question/quickblox-filtering-custom-objects-with-javascript/

Waterline ORM equivalent of insert on duplicate key update

I have a table user_address and it has some fields like
attributes: {
user_id: 'integer',
address: 'string' //etc.
}
currently I'm doing this to insert a new record, but if one exists for this user, update it:
UserAddress
.query(
'INSERT INTO user_address (user_id, address) VALUES (?, ?) ' +
'ON DUPLICATE KEY UPDATE address=VALUES(address);',
params,
function(err) {
//error handling logic if err exists
}
Is there any way to use the Waterline ORM instead of straight SQL queries to achieve the same thing? I don't want to do two queries because it's inefficient and hard to maintain.
The answer above is less than ideal. It also has the method as part of the attributes for the model, which is not correct behavior.
Here is what the ideal native solution looks like that returns a promise just like any other waterline model function would:
module.exports = {
attributes: {
user_id: 'integer',
address: 'string'
},
updateOrCreate: function (user_id, address) {
return UserAddress.findOne().where({user_id: user_id}).then(function (ua) {
if (ua) {
return UserAddress.update({user_id: user_id}, {address: address});
} else {
// UserAddress does not exist. Create.
return UserAddress.create({user_id: user_id, address: address});
}
});
}
}
Then you can just use it like:
UserAddress.updateOrCreate(id, address).then(function(ua) {
// ... success logic here
}).catch(function(e) {
// ... error handling here
});
Make a custom model method that does what you want using Waterline queries isntead of raw SQL. You will be doing two queries, but with Waterline syntax.
Example below (if you don't know about deferred objects then just use callback syntax, but the logic is the same):
var Q = require('q');
module.exports = {
attributes: {
user_id: 'integer',
address: 'string',
updateOrCreate: function (user_id, address) {
var deferred = Q.defer();
UserAddress.findOne().where({user_id: user_id}).then(function (ua) {
if (ua) {
// UserAddress exists. Update.
ua.address = address;
ua.save(function (err) {deferred.resolve();});
} else {
// UserAddress does not exist. Create.
UserAddress.create({user_id: user_id, address: address}).done(function (e, ua) {deferred.resolve();});
}
}).fail(function (err) {deferred.reject()});
return deferred.promise;
}
};
#Eugene's answer is good but it will always run 2 operations: findOne + update or create. I believe we can optimize it further because if the record exists we just need to run update. Example:
module.exports = {
attributes: {
user_id: 'integer',
address: 'string'
},
updateOrCreate: function (user_id, address) {
return UserAddress.update({user_id: user_id}, {address: address})
.then(function(ua){
if(ua.length === 0){
// No records updated, UserAddress does not exist. Create.
return UserAddress.create({user_id: user_id, address: address});
}
});
}
}
BTW, there is an open request to implement .updateOrCreate in waterline: #790