Reputation: 149
I'm using the sequelize 6. When I'm runing findOrCreate().spread
it says "findOrCreate(...).spread is not a function". Here is my code:
const response = await Response.findOrCreate({
where: {
participantId,
questionId,
},
defaults: responseNewDetail,
})
return res.status(200).send({ status: 0, data: response })
This is working fine, but it does not seperate the created status and the model value. When I'm trying to use spread:
Response.findOrCreate({
where: {
participantId,
questionId,
},
defaults: responseNewDetail,
}).spread(function(response,created){
return res.status(200).send({ status: 0, data: response })
})
It says "Response.findOrCreate(...).spread is not a function". This is the model file(response.js):
const { Sequelize } = require("sequelize")
module.exports = (sequelize, DataTypes) =>
sequelize.define(
"Response",
{
responseId: {
type: DataTypes.INTEGER,
primaryKey: true,
allowNull: false,
field: "Response_ID",
autoIncrement: true,
},
companyId: {
type: DataTypes.INTEGER,
allowNull: false,
field: "Company_ID",
},
...
)
Response model:
const ResponseModel = require("../models/response")
const Response = ResponseModel(sequelize, DataTypes)
Does anyone know what's wrong?
Upvotes: 6
Views: 4191
Reputation: 46
eleborating Brian's Answer :-
findOrCreate
returns two values first model instance and second created status,
so you can use
const [model,created] = ModelName.findOrCreate();
(Model Response in your case)
to get created status.
Upvotes: 0
Reputation: 2775
Since you're using await, you can change:
const response = await Response.findOrCreate({
where: {
participantId,
questionId,
},
defaults: responseNewDetail,
})
return res.status(200).send({ status: 0, data: response })
to
const [ response, created ] = await Response.findOrCreate({
where: {
participantId,
questionId,
},
defaults: responseNewDetail,
})
return res.status(200).send({ status: 0, data: response })
and all will be well.
This doesn't address the spread not a function thing though. For that, I only noticed this when I upgraded sequelize from an older version (I've been using sequelize since version 1). Your example of spread really should be working but for whatever reason it does not anymore (it doesn't for me either). Typically the only time I'm using spread instead of just awaiting it is when I want to defer execution of something. Right or wrong, I've begun to tackle that by just wrapping the await/async version in:
setImmediate(async () => {
// async things here
});
Hope I helped, sorry if I didn't.
Upvotes: 4