Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to get inserted record from .create() #7071

Open
galih56 opened this issue Nov 15, 2020 · 3 comments
Open

How to get inserted record from .create() #7071

galih56 opened this issue Nov 15, 2020 · 3 comments

Comments

@galih56
Copy link

galih56 commented Nov 15, 2020

Node version: 6.14.8
"sails": "^1.2.5",
"sails-hook-apianalytics": "^2.0.3",
"sails-hook-organics": "^2.0.0",
"sails-hook-orm": "^2.1.1",
"sails-hook-sockets": "^2.0.0",
"sails-mysql": "^1.0.1",
"sails-postgresql": "^2.0.0",
"winston": "^3.3.3",
"grunt": "1.0.4",
"sails-hook-grunt": "^4.0.0"


I want to create records for 2 different models.
These are my models


//project.js

module.exports = {
  tableName: 'projects',
  primaryKey: 'id',
  attributes: {
    id: {
      columnName: 'id',
      type: 'number',
      autoIncrement: true,
      unique: true
    },
    title: {
      type: 'string',
      columnName: 'title',
    },
    description: {
      type: 'string',
      columnName: 'description',
    },
    members: {
      collection: 'ProjectMember',
      via: 'project'
    },
    createdAt: { columnName: 'created_at', type: 'ref', columnType: 'timestamp' },
    updatedAt: { columnName: 'updated_at', type: 'ref', columnType: 'timestamp' }
  },
};


//ProjectMember.js

module.exports = {
  tableName: 'project_members',
  attributes: {
    id: {
      columnName: 'id',
      type: 'number',
      autoIncrement: true,
      unique: true
    },
    user: {
      columnName: 'users_id',
      model: 'User', // many to 1 with user
    },
    taskMember: {
      collection: 'TaskMember',
      via:'members'
    },
    project: {
      columnName: 'projects_id',
      model: 'Project',
      required: true,
    },
    role: {
      columnName: 'roles_id', //member has 1 role
      model: 'MemberRole',
    },
    comments:{
      collection:'Comment',
      via:'creator'
    },
    createdAt: { columnName: 'created_at', type: 'ref', columnType: 'timestamp'},
    updatedAt: { columnName: 'updated_at', type: 'ref', columnType: 'timestamp'}
  },
};

Inside a controller, i have action that can create a project and create the first project member afterward. The ProjectMember model requires project ID. But i can't get the inserted data after executing the query. It always return undefined

//UserController.js
createProject : async function(req,res){
    	let params=req.allParams();
    	let users_id=params.users_id

		try {
			const newProject={ 
			            	title: params.title,  description: params.description,  
			            	createdAt: moment().tz('Asia/Jakarta').format('YYYY-MM-DD HH:mm:ss'), 
			            	updatedAt: moment().tz('Asia/Jakarta').format('YYYY-MM-DD HH:mm:ss'),
			            }
			await Project.create(newProject)
	        			.fetch().exec( async function(err, project){
							if(err) {
								console.log(err);
								return res.send(err);
							}
							
							//Create first member of current project
							const newMember={ 
								projects_id:project.id,  //ERROR : CANNOT GET ID FROM UNDEFINED
								users_id:users_id,
								roles_id:2, //Project Creator
								createdAt: moment().tz('Asia/Jakarta').format('YYYY-MM-DD HH:mm:ss'), updatedAt: moment().tz('Asia/Jakarta').format('YYYY-MM-DD HH:mm:ss'),
							}
 							await ProjectMember.create().catch((error)=>{
								console.log(error);
								return res.serverError(error);
							});
				          	return res.ok(project);
				        }).catch((error)=>{
							console.log(error);
							return res.serverError(error);
						});
	    }
	    catch (err){
	    	return res.serverError(err);
	    }
    },

i don't understand why it can't get the inserted record. I already execute the query with exec() and use a callback.

@sailsbot
Copy link

@galih56 Thanks for posting! We'll take a look as soon as possible.

In the mean time, there are a few ways you can help speed things along:

  • look for a workaround. (Even if it's just temporary, sharing your solution can save someone else a lot of time and effort.)
  • tell us why this issue is important to you and your team. What are you trying to accomplish? (Submissions with a little bit of human context tend to be easier to understand and faster to resolve.)
  • make sure you've provided clear instructions on how to reproduce the bug from a clean install.
  • double-check that you've provided all of the requested version and dependency information. (Some of this info might seem irrelevant at first, like which database adapter you're using, but we ask that you include it anyway. Oftentimes an issue is caused by a confluence of unexpected factors, and it can save everybody a ton of time to know all the details up front.)
  • read the code of conduct.
  • if appropriate, ask your business to sponsor your issue. (Open source is our passion, and our core maintainers volunteer many of their nights and weekends working on Sails. But you only get so many nights and weekends in life, and stuff gets done a lot faster when you can work on it during normal daylight hours.)
  • let us know if you are using a 3rd party plugin; whether that's a database adapter, a non-standard view engine, or any other dependency maintained by someone other than our core team. (Besides the name of the 3rd party package, it helps to include the exact version you're using. If you're unsure, check out this list of all the core packages we maintain.)

Please remember: never post in a public forum if you believe you've found a genuine security vulnerability. Instead, disclose it responsibly.

For help with questions about Sails, click here.

@rachaelshaw
Copy link
Member

Hi @galih56, you don't need .exec() when using await. Try this:

var project = await Project.create(newProject).fetch();

Hope that helps!

@Ibrahim-Achkar
Copy link

Hi @galih56, you don't need .exec() when using await. Try this:

var project = await Project.create(newProject).fetch();

Hope that helps!

it certainly helped me, thank you so much!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Development

No branches or pull requests

5 participants