Reputation: 23
I try to create an associated table of tags with id of tag and id of related article, so first i do a findOrCreate tag, this function is operational and works perfectly, but when i do a then(function(result){}) and with the result i create my association with the id of the tag like result.id the id returned is null ! So in the case where i do a simple create it returns me an id, but when i do a findOrCreate the id is null !! What can i do to get the id of my created entry with findOrCreate function ? if there's another solution to create an entry that not already existing i'm also interested....here's my function in app.js
function(sales, callback) {
if(req.body.tags) {
tagsArray = req.body.tags.split(',');
var obj = tagsArray.reduce(function(acc, cur, i) {
acc[i] = cur;
return acc;
}, {});
callback(null, async.forEachOf(obj, (value,key,callback) => {
tagsFormattedArray.push({tags: value})
tagsController.create(req, res, value).then(function(result){
callback(null, tagSpottingController.create(req, res, result.id, idCreation))
})
}))
}
}
here's my tag controller :
module.exports = {
create(req, res, tag) {
return Tags
.findOrCreate({
where: {
name: tag
},
defaults: {
name: tag
}
})
}
};
here is my tag model :
module.exports = (sequelize, DataTypes) => {
const Tags = sequelize.define('Tags', {
id: {
type: DataTypes.INTEGER,
autoIncrement: true,
primaryKey: true
},
name: {
type: DataTypes.STRING
},
createdAt: {
type: DataTypes.DATE,
field: 'createdAt'
},
updatedAt: {
type: DataTypes.DATE,
field: 'updatedAt'
}},{
timestamps: true
});
return Tags;
}
I read the doc and i tested to do this in my tag controller :
module.exports = {
findOrCreate(req, res, tag) {
return Tags
.findOrCreate({
where: {
name: tag
},
defaults: {
name: tag
}
}).spread((tags, created) => {
console.log(tags.get({
plain: true
}))
})
}
};
It console log all my created tags (the ones who are not in the db) that the behaviour that i wanted !...but when i try to do a return instead of a console log , to get my ids, it returns me only the false result (the one which already exists in the db)...there something that i don't understand
Upvotes: 1
Views: 1511
Reputation: 23
It seems that we cannot directly return the result of the spread so i had to push it inside a callback. Here my final code :
tagsController.findOrCreate(req, res, value).spread(function(tags, created){
if (created){
callback(null, tagSpottingController.create(req, res, tags.id, idCreation))
}
else {
callback(null, tagSpottingController.create(req, res, tags.id, idCreation))
}
})
Upvotes: 0