I'm creating a rest service with knex and bookshelf. I want to return all the record with a user specific field which is not in the database.
A good example would be a IsFavorite boolean field on a Book list request. I would then show something else to the user for a favorite book.
Now let's say I have 3 tables: User, Book and Favorite. How would I code the "get" IsFavorite field from the book record?
I saw that bookshelf support virtuals by doing something like this :
var User = Bookshelf.Model.extend({
tableName: 'users',
outputVirtuals: true,
virtuals: {
fullName: function() {
return this.get('firstName') + ' ' + this.get('lastName');
}
},
});
but I can't figure out how to fetch from my Favorite table within the virtuals.
Thank you
Related
I am so completely lost. I have an explicit many to many relation: Users can have multiple Lists, but lists can be owned by multiple users:
model List {
id String #id #default(cuid())
title String
users UsersOnLists[]
}
model User {
id String #id #default(cuid())
name String
lists UsersOnLists[]
}
model UsersOnLists {
id String #id #default(cuid())
order Int
user DictItem? #relation(fields: [userId], references: [id])
userId String?
list List? #relation(fields: [ListId], references: [id])
listId String?
}
Now I'd like to connect a list to a user:
prisma.list.update({
where: {
id: input.id
},
data: {
users: {
create: [{
order: 123,
user: {
connect: {
id: "abcd-123",
}
}
}],
}
}
});
This works.
However, I don't know how to go about disconnecting many-to-many relations in prisma? Say I want to disconnect the user again from the list? How would I do this?
prisma.list.update({
where: {
id: input.id
},
data: {
users: {
disconnect: [{
user: {
disconnect: {
id: "abcd-123",
}
}
}],
}
}
});
This doesn't work.
I also can't find much in the prisma docs about disconnecting. Any ideas?
I guess I could jus delete the row from the Relations-Table, but this doesn't feel as clean and I guess I would still have the old ids in the user & list tables? I would prefer using disconnect, if this is the recommended method for that.
Are you getting a specific error? If you are using a code editor/IDE with TypeScript hinting, it should be giving you a specific error(s) about what's going on. If not that, then the command line should be giving you errors when you attempt to run an operation.
Docs: https://www.prisma.io/docs/concepts/components/prisma-client/relation-queries#disconnect-a-related-record
The "disconnect" operation cannot disconnect deeply-nested relations. It only disconnects documents directly connected to the model in question. In your situation, you can only disconnect a UserOnList from a List, but you cannot also disconnect User from UserOnList in the same operation.
prisma.list.update({
where: {
id: input.id
},
data: {
users: {
disconnect: [{
id: "ID_OF_UsersInList_MODEL_HERE"
}],
}
}
});
Also - you don't need the UsersInList table. Prisma can manage the "join" table under the hood for you if you don't need any extra information or data on that model. Check out the docs here if you want Prisma to manage this table on its own: https://www.prisma.io/docs/concepts/components/prisma-schema/relations/many-to-many-relations
I have postgres table name tests which contain few records, now I want to fetch all record of this table but unable because its provides only id,createdAt and updatedAt.
So either I have to provide an object which contain column name that I don't want, I wish it should be dynamic so after this if I pass another table name it will provide data of that.
I tried this but it returns null array of object
Project.findAll(attributes: ['*']
}).then(function(project) {
console.log("select_data: " + JSON.stringify(project));
})
I'm not totally clear on what the question / problem is here, but it sounds like when you're defining your model, you might not have included all the column names of the table in your model definition. Here's what it should look like:
module.exports = function(sequelize, DataTypes) {
const test = sequelize.define('test', {
my_column: DataTypes.STRING,
my_other_column: DataTypes.STRING,
my_boolean_column: DataTypes.BOOLEAN,
}, {
timestamps: true,
underscored: true,
tableName: 'tests',
})
return test
}
Notice each column of the table is explicitly defined in the model.
How do i achieve the following relation in bookshelf.js
SELECT user_accounts.user_id, `event_id`
FROM `calendar_events`
JOIN user_accounts ON user_accounts.user_id = calendar_events.`created_by`
LIMIT 10
My Model
var CalendarEvent = bookshelf.Model.extend({
tableName: 'calendar_events',
hasTimestamps: ['created_on'],
user: function() {
return this.hasOne('UserAccount','user_id');
}
});
var UserAccount = bookshelf.Model.extend({
tableName: 'user_account'
});
If you wanted to get that exact style query, you could use the knex query builder and try to build a query to match your needs
have not tested this but should be something like this
CalendarEvent.forge().query(function(qb){
qb.join('user_accounts', 'user_accounts.user_id', '=', 'calendar_events.created_by');
//qb.where() //if you wanted
//qb.andWhere(); //and if you wanted more
qb.limit(10);
})
.fetchAll();
(you dont need the .where or .andWhere, just added those for fun)
It might be possible to do it purely in bookshelf, but i'm not sure of how at the moment.
I suppose you found the solution since 2016 but here is the answer
var CalendarEvent = bookshelf.Model.extend({
tableName: 'calendar_events',
hasTimestamps: ['created_on'],
user: function() {
return this.belongsTo(UserAccount, 'user_id', 'created_by');
}
});
var UserAccount = bookshelf.Model.extend({
tableName: 'user_account'
});
Use belongsTo() method because the foreign key is in the CalendarEvent Model and not in the UserAccount model. Append the name of the foreign key to belongsTo() parameters to specify the name of the foreign key.
Then, use the Bookshelf model like this :
CalendarEvent
.forge()
.fetchPage({ pageSize: 10, withRelated: ['user'] })
.then(data => {
// Data retrieval
})
.catch(exc => {
// Error management
});
The fetchPage method uses page and pageSize to create a pagination. You will retrieve a data.pagination object containing rows info (number to rows, page number, page size, page total count) and data.toJSON() will retrieve your models.
I know that the classic way to add data to user collection is in profile array, but according to this document, it is not the best way to store data.
Is there an alternative to that, for example to create a field in the root of user collection at the same level with default fields (_id, username, etc.)?
There is nothing wrong per-se with the profile field, other than the fact that a users can (currently) directly update their own profile by default.
I don't find this behavior desired, as a user could store arbitrary data in the profile.
This may become a real security risk if the developer uses that field as a source of authority; for example, stores the user's groups or roles in it.
In this case, users could set their own permissions and roles.
This is caused by this code:
users.allow({
// clients can modify the profile field of their own document, and
// nothing else.
update: function (userId, user, fields, modifier) {
// make sure it is our record
if (user._id !== userId)
return false;
// user can only modify the 'profile' field. sets to multiple
// sub-keys (eg profile.foo and profile.bar) are merged into entry
// in the fields list.
if (fields.length !== 1 || fields[0] !== 'profile')
return false;
return true;
}
});
The first thing to do is to restrict writes to it:
Meteor.users.deny({
update() {
return true;
}
});
It could then be updated using methods and other authorized code.
If you add your own fields and want to publish them to the currently logged-in user, you can do so by using an automatic publication:
Meteor.publish(null, function () {
if (this.userId) {
return Meteor.users.find({
_id: this.userId
}, {
fields: {
yourCustomField1: 1,
yourCustomField2: 1
}
});
} else {
return this.ready();
}
});
Meteor.users is just a normal Mongo.Collection, so modifying it is done just like any other Collection. There is also the creation hook, Accounts.onCreateUser which allows you to add custom data to the user object when it is first created, as mentioned in #MatthiasEckhart's answer.
You could add extra fields to user documents via the accountsServer.onCreateUser(func) function.
For example:
if (Meteor.isServer) {
Accounts.onCreateUser(function(options, user) {
_.extend(user, {
myValue: "value",
myArray: [],
myObject: {
key: "value"
}
});
});
}
Please note: By default, the following Meteor.users fields are published to the client username, emails and profile. As a consequence, you need to publish any additional fields.
For instance:
if (Meteor.isServer) {
Meteor.publish("user", function() {
if (this.userId) return Meteor.users.find({
_id: this.userId
}, {
fields: {
'myValue': 1,
'myArray': 1,
'myObject': 1
}
});
else this.ready();
});
}
if (Meteor.isClient) {
Meteor.subscribe("user");
}
A few questions about storing user data in MongoDB. What is the best place in mongo to store user specific data, such as User settings, User photo url, User friends, User events?
In Mongo, user data is stored in:
Meteor
/ Collections
/ users
/ _id
/ profile
/ services
Should I add there a new collections? In a following way:
/ events / _id's
/ friends / _id's
/ messages / _id's
/ settings
How should I publish user's private data and manipulate this collections, to be sure it's save and no one else will modify or have access to private data of another person.
You can add data to the users profile field like this:
Meteor.users.update( id, { $set: { 'profile.friends': someValue } } );
To only publish specific fields you can do something like this:
Meteor.publish( 'users', function () {
return Meteor.users.find( {}, { fields: { 'profile.friends': 1 } } );
});
Hope this helps.
Normalization
"Database normalization is the process of organizing the attributes and tables of a relational database to minimize data redundancy."
MongoDB is a non relational database. This makes normalized data hard to query for. This is why in MongoDB we denormalize data. That makes querying for it easier.
It depends on your use-case. The question is basically when to demormalize. It's mostly a matter of opinion. But objective here are some pros and cons:
Pros to demormalization
It's easier to retrieve data (Due to Mongo not beeing a relational DB)
It performs better if you are always getting the data in bulk
Cons to demormalization
It doesn't scale well for things like user.messages (You can't just publicize some messages)
In your case I'd definitly go for seperate collections for events, friends and messages. Setting can't expand infinitly. So I'd put it into the users collection.
Security
I'd use a publications and allow and deny for this. Let me make an example for Messages:
Collection
Messages = new Mongo.Collection('Messages')
Messages.insert({
sender: Meteor.userId,
recipient: Meteor.users.findOne()._id,
message: 'Hello world!'
})
Publication
Meteor.publish('userMessages', function (limit) {
return Messages.subscribe({
$or: [
{sender: this.userId},
{recipient: this.userId}
]
}, {limit: limit})
})
Allow
function ownsMessage (user, msg) {
return msg.sender === user ? true : false
}
Messages.allow({
insert: function (userId, newDoc) {
!!userId
},
update: function (userId, oldDoc, newDoc) {
if(
ownsMessage(userId, oldDoc) &&
ownsMessage(userId, newDoc)
) return true
return false
},
remove: function () {
return false
}
})
This code is untested, so it might contain small errors