sails: create().fetch() is not a function error.
Sails version: v1.0.2 Node version: v10.7.0 NPM version: 6.2.0 DB adapter name: sails-mongo DB adapter version: 1.0.1 Operating system: mac
Hi everyone, I’m trying to insert a data and calling fetch() to return the new data that have been created. But I’m getting this error TypeError: User.create(...).fetch is not a function. Without the fetch it works fine. I’m not sure whether this is sails or waterline issue.
I have tested using meta({fetch: true}) and the result is the same. Meta is not a function.
The only way I can get something similar to fetch is to enable fetchRecordsOnCreate on config/models.js but I know this is a temporary fixed.
This is my file UserController.js
register: async function(req, res){
try{
const user = await User.create({name:req.body.name, email: req.body.email, password: req.body.password}).fetch()
return res.ok(user);
}
catch(err)
{
console.log(err);
return res.serverError({'err':err});
}
},
User.js
/**
* User.js
*
* @description :: A model definition. Represents a database table/collection/etc.
* @docs :: https://sailsjs.com/docs/concepts/models-and-orm/models
*/
const bcrypt = require("bcryptjs")
module.exports = {
attributes: {
name: {
type: 'string',
required: true
},
roles: {
type: 'json',
columnType: 'array',
defaultsTo: ["DEFAULT_USER"]
},
email: {
type: 'string',
unique: true,
isEmail: true,
required: true
},
password: {
type: 'string',
required: true
},
tickets: {
collection: 'ticket',
via: 'assign_user'
}
},
customToJSON: function () {
return _.omit(this, ['password'])
},
/**
* this is called so we can create our password hash for us
*
* before saving
* @param values
* @param cb
*/
beforeCreate: function (values, cb) {
// Hash password
bcrypt.hash(values.password, 10, function (err, hash) {
if (err) return cb(err)
values.password = hash
cb()
})
}
}
About this issue
- Original URL
- State: closed
- Created 6 years ago
- Comments: 20 (3 by maintainers)
For me, I upgraded to Sails 1.4 and got the above error. Eventually, I discovered that I had the “sails-hook-validation” package installed. Worked after uninstalling “sails-hook-validation”
I encountered this issue and although I’m not sure why
Something.create(data)doesn’t work, something that works issails.models.something.create(data)@valehelle Yeah I was wrong about that, sorry.
Removing the try / catch block should solve the issue. Not entirely sure why, could it be a scope problem? I know that Sails also handles exceptions internally. So it might not be needed for error handling models.