How to append nodejs sequelize model list of json field - javascript

How to append a list of JSON filed in nodejs Sequelize
database: Postgres
I have one model field like that :
student_list:
{
type: Sequelize.ARRAY(Sequelize.JSON),
allowNull: true
},
I am trying to append Sequelize Array of JSON like this way but not get sucessfully append list:
var data = ({'share_by':"aaa",'list_name':"list_name"})
student.update(
{'student_list': Sequelize.fn('array_append', Sequelize.col('student_list'), data)},
{'where': {studet_id: student_id}}
);
how to do this?

You can do a find() and get the element value, update the element and do a update with data updated. Like this:
// Get the actual student data
const student = await student.findOne(studentId);
// Spread and add the new value
const student_list = {
...student_list,
data
};
// Update the field
await student.update(
{
student_list
},
{
where: {
student_id
}
}
);

Related

Realtime database update or create functionality

I have a user object in firebases realtime database. I am querying realtime database and when successful I am wanting to write some new data to the user object under the users node.
My desired outcome: When a user has not fetched the information before, a new field called 'lastViewed' under the user object is created and if the field has already been created then we update the timeViewed keys value. A user can have multiple objects in the array corresponding to the uuid of the fetched data.
Please see the user object below
This may not need to be an array if using .push()
-N0X8VLHTw3xgvD2vJs- : { // this is the users unique key
name: 'myName',
lastViewed: {
[
{
timeViewed: 1651558791, // this is the field to update if exists
datasUniqueKey: 'N17ZmwIsbqaVSGh93Q0' // if this value exists update timeViewed else we create the entry.
},
{
timeViewed: 1651558952,
datasUniqueKey: 'N17ZmwIsbqaVSad3gad'
},
]
}
}
Please see my attempt below.
const getData = database()
.ref(`data/${uniqueKeyFromData}`)
.on('value', snapshot => {
if (snapshot.exists()) {
database()
.ref(`users/${currentFirebaseUserKey}/lastViewed`) // currentFirebaseUserKey = N0X8VLHTw3xgvD2vJs
.once('value', childSnapshot => {
if (childSnapshot.exists()) {
// update
database()
.ref(
`users/${currentFirebaseUserKey}/lastViewed`,
)
.update({
timeViewed: new Date(), // new data will not give us the corresponding date format in the user object above but don't worry about that
fetchedDatasUniqueKey: uniqueKeyFromData,
});
} else {
// create
database()
.ref(
`users/${currentFirebaseUserKey}/lastViewed`,
)
// Push creates a unique key which might not be required so maybe set?
.push({
timeViewed: new Date(),
fetchedDatasUniqueKey: uniqueKeyFromData,
});
}
});
}
});
Where I think I am going wrong
Above I am not creating an array, if I use push I would get a unique key generated from firebase but then would have to use that key when updating, something like
`users/${currentFirebaseUserKey}/lastViewed/${lastViewedUniqueKey}`
So the user object would look like so
-N0X8VLHTw3xgvD2vJs- : { // this is the users unique key
name: 'myName',
lastViewed: {
-N17i2X2-rKYXywbJGmQ: { // this is lastViewedUniqueKey
timeViewed: 1651558791,
datasUniqueKey: 'N17ZmwIsbqaVSGh93Q0'
},
}
}
then check for snapshot.key in the if?, any help would be appreciated.
Since you don't want a list of data, but a single set of properties for ``, you should just call set instead of push:
database()
.ref(`users/${currentFirebaseUserKey}/lastViewed`)
.set({ // 👈
timeViewed: new Date(),
fetchedDatasUniqueKey: uniqueKeyFromData,
});
I also don't think you need the two different cases here for create vs update, as both seem to do the exact same thing. If you do need both cases though, consider using a transaction.

How do I get a virtual in mongoose, If a property is deselected

lets say I have post Model and schema contains UserId , Title, Desc and likes array which takes userId's as ref
when I make a query I get a virtual property like this to find out num of like of a post would have
schema.virtual("numLikes").get(function () {
return this.likes.length;
});
But the problem is when I run the findById() Method I dont want to get likes from database because likes array would contain large list of users
const post = await Post.findById(postId).select("-likes -shares");
so how do I get Likes count without fetching likes array ?
I believe this can be done using aggregation, by using the $size operators in a projection:
const aggregate = Post.aggregate([
{ $match: {_id: postId}},
{ $project: {
numberOfLikes: { $size: "$likes" }
}
}
]);
https://docs.mongodb.com/manual/reference/operator/aggregation/size/
https://mongoosejs.com/docs/api/aggregate.html#aggregate_Aggregate-project

Sequelize user.increment("somethings") do not update the value

when I try to increment something with sequelize it doesn't return me the updated value (incremented) and to get that I need to reuse findOne method.
Looking in the sequelize doc here in the increment section you can read this:
The updated instance will be returned by default in Postgres. However,
in other dialects, you will need to do a reload to get the new values.
Is ther any way to "fix" it without using this "workaround" ( recalling findOne )?
const user = await Tags.findOne({
where: { id: ID },
});
await user.increment("rank");
const user1 = await Tags.findOne({
where: { id: ID },
});

Mongo update removing other keys in document

I am trying mongo update where one document key from a different collection is inserted into another collection.
CODE
// update user document with remove of otp and new state set.
updateOne = await db.collection(_collection).updateOne(
// search basis.
__docUpdateSearchBasis,
// updates.
__docUpdateBasis
)
RESULT
You need to make query like this:
updateOne = await db.collection(_collection).findOneAndUpdate(
//Condition
{
_id: req.user.id
},
//Update what you want
{
$set: {
key: value
}
});

Join in bookshelf.js

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.

Categories