Sails: create().fetch() is not a function error.

Created on 10 Sep 2018  路  19Comments  路  Source: balderdashy/sails


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()
    })
  }
}

All 19 comments

Hi @valehelle! It looks like you may have removed some required elements from the initial comment template, without which I can't verify that this post meets our contribution guidelines. To re-open this issue, please copy the template from here, paste it at the beginning of your initial comment, and follow the instructions in the text. Then post a new comment (e.g. "ok, fixed!") so that I know to go back and check.

Sorry to be a hassle, but following these instructions ensures that we can help you in the best way possible and keep the Sails project running smoothly.

*If you feel this message is in error, or you want to debate the merits of my existence (sniffle), please contact [email protected]

ok, fixed!

@valehelle Thanks for posting, we'll take a look as soon as possible.


For help with questions about Sails, click here. If you’re interested in hiring @sailsbot and her minions in Austin, click here.

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.

I remove the try / catch block but the problem still persist

Create automatically returns the new record, so that is why there is no .fetch() function for it.

@valehelle Yeah I was wrong about that, sorry.

@valehelle - I noticed there's no semicolon at the end of .fetch() in your example - is that missing from the actual code? Also, I'm curious if you've seen this issue with the latest Sails v1.1.0 or with other adapters and their databases besides sails-mongo? Being that this function is passed through both Sails and the underlying database adapter sails-mongo, it may be worth verifying if the sails-mongo adapter is installed and configured properly as well. I wonder if this is a potential query translation issue with the .fetch() pass through Waterline into sails-mongo?

@valehelle what version of sails-hook-orm are you using?

(can't reproduce this)

I'm currently facing thesame issue and this is 2019 and it seems this issue hasn't been resolved yet....

I get this error everytime i try to get a newly created
TypeError: Hobby.create(...).fetch is not a function

My application dependencies

> "dependencies": {
>     "@sailshq/connect-redis": "^3.2.1",
>     "@sailshq/lodash": "^3.10.3",
>     "@sailshq/socket.io-redis": "^5.2.0",
>     "bcrypt": "^3.0.6",
>     "body-parser": "^1.19.0",
>     "cookie-parser": "^1.4.4",
>     "dotenv": "^8.0.0",
>     "grunt": "1.0.4",
>     "jsonwebtoken": "^8.5.1",
>     "passport": "^0.4.0",
>     "passport-jwt": "^4.0.0",
>     "passport-local": "^1.0.0",
>     "sails": "^1.2.3",
>     "sails-hook-grunt": "^4.0.0",
>     "sails-hook-orm": "^2.1.1",
>     "sails-hook-sockets": "^2.0.0",
>     "sails-hook-validation": "^0.4.7",
>     "sails-mongo": "^1.0.1",
>     "striptags": "^3.1.1"
>   }

what could i have done wrong , i followed the examples provided here https://sailsjs.com/documentation/reference/waterline-orm/models/create but yet i still get that same error

@TheDhejavu Mine is working properly, [in 2019]

Book.create(_.extend(inputs, { user: this.req.me.id }))
      .intercept("E_UNIQUE", "bookAlreadyExist")
      .intercept({ name: "UsageError" }, "invalid")
      .fetch();

// Viola! it works

My dependencies

  "dependencies": {
    "@sailshq/connect-redis": "^3.2.1",
    "@sailshq/lodash": "^3.10.3",
    "connect-mongo": "2.0.3",
    "faker": "^4.1.0",
    "moment": "^2.24.0",
    "nodemailer": "^6.3.0",
    "nodemailer-mailgun-transport": "^1.4.0",
    "sails": "^1.2.2",
    "sails-hook-apianalytics": "^2.0.3",
    "sails-hook-cloud": "^0.1.1",
    "sails-hook-organics": "^1.0.0",
    "sails-hook-orm": "^2.1.1",
    "sails-hook-sockets": "^2.0.0",
    "sails-hook-uploads": "^0.4.3",
    "sails-mongo": "^1.0.1"
  },

can you reproduce your issue on a fresh sails app and share the repo? maybe you're missing something - not sure

@navicstein this is the code block

create: async function(req, res){

    let { id: userId } = req.user;
    let { name } = req.body;

    if(!name || name == ""){
      return res.badRequest(null, null, "Hobby name is missing")
    }

    try{
      let uid = shortid.generate();
      let data = {
        name:  striptags(name),
        userId: userId,
        uid: uid
      }
      await  Hobby.create( data ).fetch()

      if(hobby){
        return res.created(hobby);
      }else{
        return res.badRequest(null, null, "Something went wrong")
      }
    }catch(error){
      console.log( error );
      return res.serverError(error)
    }
  },

Hobby.js Model

module.exports = {

  attributes: {
    userId:{
      type: "string",
      required: true
    },
     name: {
      type: 'string',
      required: true,
    },
    uid:{
      type: "string",
      required: true
    }

  },
};

Still not working

@TheDhejavu do you mean

let hobby = await Hobby.create( data ).fetch()

@TheDhejavu it should work but looks like you're using traditional controllers, can you replicate this using actions 2 [i don't really have time to re-write yours]
[http://node-machine.org/spec/machine](http://node-machine.org/spec/machine)

why do i have to follow actions2 to fetch! it's really exhausting to create actions2 for each and every action!!
Plus the guides only include one action module.exports={...bla}

I encountered this issue and although I'm not sure why Something.create(data) doesn't work, something that works is sails.models.something.create(data)

@onedebos's suggestion fixed this for me

Was this page helpful?
0 / 5 - 0 ratings