How to update an array in Sequelize Postgres - node.js

I have a user model in Sequelize for a Postgres db:
var User = sequelize.define('User', {
fb_id: DataTypes.STRING,
access_token: DataTypes.TEXT,
first_name: DataTypes.STRING,
last_name: DataTypes.STRING,
email: DataTypes.TEXT,
profilePictureURL: DataTypes.TEXT,
library: DataTypes.ARRAY(DataTypes.STRING)
}, {
underscored: true,
classMethods: {
associate: function(models) {
}
}
});
I am trying to update the library field by adding ISBNs to the array. This is the code for my POST request:
req.user.library.push(req.body._isbn); // adding the posted ISBN to the user object in my express-session
User.findOrCreate({where: {fb_id: req.user.fb_id},
defaults: {
access_token : req.user.access_token,
first_name : req.user.first_name,
last_name : req.user.last_name,
email : req.user.email,
profilePictureURL : req.user.profilePictureURL,
library: req.user.library // new library object
}})
.spread(function (updatedUser, created){
res.status(200).json(updatedUser);
}).error(function(err){
res.status(500).json(err);
});
There is no error, but the library field is not updated after checking the updatedUser object. How do I correctly update an array field in Sequelize?

For next visitors, I may have found a better way to solve this issue :
User.update(
{library: Sequelize.fn('array_append', Sequelize.col('library'), req.body._isbn)},
{where: {fb_id: req.user.fb_id}}
);

I ran into this before and found the answer deep in their Github issues. The way I accomplished it is
User.find({
where: {
fb_id: req.user.fb_id
}
})
.then((user) => {
user.library.push(req.body._isbn)
user.update({
library: user.library
},{
where: {
fb_id: req.user.fb_id
}
})
.then(user => res.json(user))
})
It definitely feels like there is a better way, but this way how I found a way.

Kinda old issue but I found a workaround that could help in the future, from what I understand sequelize may not recognize an updated data as new instance so it will consider it as local scope only. Solution for me was to create a new object upon the needed array, something like:
let newArray = Object.assign([], instance.arrayToUpdate);
newArray.push(myInterestingData)
await instance.update({
arrayToUpdate: newArray
});

Related

Sequelize magic method not found using Express and Node.JS

I'm coding an application using Sequelize, Express and Node.JS; after set a OneToMany relationship between User and Product, just like this:
app.js:
Product.belongsTo(User, { constraints: true, onDelete: 'CASCADE' });
User.hasMany(Product);
and from a controller called admin.js I'm trying to create a new Product using a magic method:
admin.js:
exports.postAddProduct = (req, res, next) => {
const title = req.body.title;
const imageUrl = req.body.imageUrl;
const price = req.body.price;
const description = req.body.description;
req.user.createProduct({
title: title,
imageUrl: imageUrl,
price: price,
description: description
})
.then((result) => {
console.log("Record successfully created");
return res.redirect("/admin/products");
})
.catch((err) => {
console.log(err);
});
};
postAddProduct is triggered after submit a form, the error I'm getting is this:
So, my question is: based on sequelize's official documentation, after define a relationship I can use methods for create, edit o search an entity, what am I missing to get access to these methods?
thanks for your comments
even though my model is called Product, the table's name is newproducts, so, in order to solve this I made this change:
req.user.createNewproduct({
title: title,
imageUrl: imageUrl,
price: price,
description: description })
After this, problem solved
Nice to see someone else taking Max's Node.js course!
I had this same problem. For me, it stemmed from the fact that I defined how my id column works differently. Instead of this...
id: {
type: Sequelize.INTEGER,
autoIncrement: true,
allowNull: false,
primaryKey: true
},
...I did this...
id: {
type: Sequelize.UUID,
defaultValue: Sequelize.UUIDV4,
allowNull: false,
primaryKey: true,
},
and utilized the uuid package to make unique Product and User IDs. Because of this, I had to update how I defined my SQL relations in app.js:
Product.belongsTo(User, { constraints: true, onDelete: "CASCADE" });
User.hasMany(Product, { foreignKey: "id" });
So if you're using a custom ID generator or something, make sure to specify that you are in the options object and the function should appear!
You can read more about this in the docs: https://sequelize.org/docs/v6/core-concepts/assocs/#defining-the-sequelize-associations
Hope this helps!

MongoDB element on nested schemas and return only that element

i have this Schema for a simple twitter app
const userSchema = new Schema ({
loginInfo: {
username: String,
email: String,
password: String
},
tweets: [{
content: String,
likes: Number,
comments: [{
owner: String,
content: String,
likes: Number
}]
}],
followers: [String],
following: [String]
})
and i want to make endpoint that return only the tweet that has the same _id that has been given as a params on the URL ..
I made that solution below and its working correctly but i believe there is a much better solution than this ..
const handleTweet = (User) => (req,res) => {
const { id } = req.params;
let theTweet = [];
User.findOne({ "tweets._id": id})
.then(user => {
user.tweets.forEach(tweet => {
if(tweet._id.toString() === id)
return theTweet.push(tweet)
})
res.json(theTweet)
})
.catch(err => res.json(err))
}
module.exports = handleTweet;
One more question : Is it better to make nested schemas like this or making a different models for each schema (in this case schema for User and another one for Tweets) ?
You should make the tweets into a different collection since you are querying based on that, and then you can use autopopulate when you need it.
Also instead of the foreach you could use Array.prototype.find
Hope this helps!
You can use the $push & findOneAndUpdate methods from mongoose. You can modify your example to be like this:
User.findOneAndUpdate(id, { $push: { tweets: req.body.tweet } }, {new: true})
.then((record) => {
res.status(200).send(record);
})
.catch(() => {
throw new Error("An error occurred");
});
Notice the {new: true} option, it makes the findOneAndUpdate method to return the record with the edit.
For your second question, it's recommended to split the modals to make your code more readable, maintainable and easy to understand.

Mongoose - trying to do 'JOINS' in MEAN stack

I am having a hard time understanding the async nature of NodeJS.
So, I have an articles object with this schema:
var ArticleSchema = new Schema({
created: {
type: Date,
default: Date.now
},
title: {
type: String,
default: '',
trim: true,
required: 'Title cannot be blank'
},
content: {
type: String,
default: '',
trim: true
},
creator: {
type: Schema.ObjectId,
ref: 'User'
}
});
and the User schema is:
var UserSchema = new Schema({
firstName: String,
lastName: String,
...
});
The problem is when I query for all the documents like so:
exports.list = function(req, res) {
// Use the model 'find' method to get a list of articles
Article.find().sort('-created').populate('creator', 'firstName lastName fullName').exec(function(err, articles) {
if (err) {
// If an error occurs send the error message
return res.status(400).send({
message: getErrorMessage(err)
});
} else {
// Send a JSON representation of the article
res.json(articles);
}
});
};
I get all the articles back successfully, but for some reasons, the article creator is returning different results
for locally authenticated users (localStrategy) and facebook authenticated users (facebook strategy) for locally authenticated users, I get:
articles = {
creator: {
id: 123,
firstName: 'Jason',
lastName: 'Dinh'
},
...
}
for fb authenticated users, I get:
articles = {
creator: {
id: 123
},
...
}
I can't seem to get a grip on PassportJS API, so what I want to do is
iterate through articles and for each article, find the user document using the article creator ID and add the user firstName and lastName to the articles object:
for each article in articles {
User.findOne({ '_id': articles[i].creator._id }, function(err, person){
//add user firstName and lastName to article
});
}
res.json(articles);
You can probably already see the problem here... my loop finishes before the documents are returned.
Now, I know that MongoDB doesn't have any 'joins' and what I want to do is essentially return a query that 'joins' two collections. I think I'm running into problems because I don't fundamentally understand the async nature of
node.
Any help?
You can use find instead of findOne and iterate inside your callback function.
User.find({ }, function(err, personList){
for each person in personList {
for each article in articles {
if (person._id === article.creator._id) {
//add user firstName and lastName to article
}
}
}
res.json(articles);
});
UPDATE:
Considering the scenario that #roco-ctz proposed (10M users), you could set a count variable and wait for it to be equal to articles.length:
var count = 0;
for each article in articles {
User.findOne({ '_id': articles[i].creator._id }, function(err, person){
//add user firstName and lastName to article
count += 1;
});
}
while (count < articles.length) {
continue;
}
res.json(articles);

Nested query with mongoose

I have three models: User, Post and Comment
var User = new Schema({
name: String,
email: String,
password: String // obviously encrypted
});
var Post = new Schema({
title: String,
author: { type: Schema.ObjectId, ref: 'User' }
});
var Comment = new Schema({
text: String,
post: { type: Schema.ObjectId, ref: 'Post' },
author: { type: Schema.ObjectId, ref: 'User' }
});
I need to get all posts in which the user has commented.
I know it should be a very simple and common use case, but right now I can't figure a way to make the query without multiple calls and manually iterating the results.
I've been thinking of adding a comments field to the Post schema (which I'd prefer to avoid) and make something like:
Post.find()
.populate({ path: 'comments', match: { author: user } })
.exec(function (err, posts) {
console.log(posts);
});
Any clues without modifying my original schemas?
Thanks
You have basically a couple of approaches to solving this.
1) Without populating. This uses promises with multiple calls. First query the Comment model for the particular user, then in the callback returned use the post ids in the comments to get the posts. You can use the promises like this:
var promise = Comment.find({ "author": userId }).select("post").exec();
promise.then(function (comments) {
var postIds = comments.map(function (c) {
return c.post;
});
return Post.find({ "_id": { "$in": postIds }).exec();
}).then(function (posts) {
// do something with the posts here
console.log(posts);
}).then(null, function (err) {
// handle error here
});
2) Using populate. Query the Comment model for a particular user using the given userId, select just the post field you want and populate it:
var query = Comment.find({ "author": userId });
query.select("post").populate("post");
query.exec(function(err, results){
console.log(results);
var posts = results.map(function (r) { return r.post; });
console.log(posts);
});

Can a Schema use it's own model to validate?

For example, say I have a user schema, and I want to validate that the username is unique before even attempting to save the user to the database.
...
UserSchema.path('username')
.validate(function (value, respond) {
User.findOne({ username: this.username }) // This isn't valid.
.lean()
.select('_id')
.exec(function (err, user) {
if (err) {
winston.warn('User_username: Error looking for duplicate users');
respond(false);
}
// If a user was returned, then the user is non-unique!
if (user) {
respond(false);
}
respond(true);
});
});
...
var User = mongoose.model('User', UserSchema);
I know I could use mongoose.model('User').findOne(...) but that just seems a bit silly, is there no better way to do it?
You can create an unique index in your schema by setting unique: true. This will make use of the unique index option that is available in mongodb. Here is an example snippet from one of my models using this option:
// The (generated) uniform resource locator
url: {
// ... which is required ...
required: true,
// ... which is an unique index ...
unique: true,
// ... and is a string.
type: String
}
Compound key from comments:
Schema.index({ username: 1, accountCode: 1 }, { unique: true })

Resources