← back to code snippets


Vulcan JS: how to change the userID of a document

Posted on December 16th, 2019 in JavaScript by Graeme

Originally posted in the Vulcan.js slack channel, but pasting here for anyone searching:

Does anyone know how to change the userID of a document? I want admins to be able to see a select box of registered users so that they can change the document's userId...so far I'm trying this, but it only shows the currentUser in the select control - I think I just have the resolver wrong:

  userId: {
type: String,
optional: true,
canRead: ['guests'],
editableBy:['admins'],
control:'select',
options: function () {
var users = Meteor.users.find().map(function (user) {
return {
value: user._id,
label: getDisplayName(user)
}
});
return users;
},
resolveAs: {
fieldName: 'user',
type: 'User',
resolver: (movie, args, context) => {
return context.Users.findOne({ _id: movie.userId }, { fields: context.Users.getViewableFields(context.currentUser, context.Users) });
},
addOriginalField: true
}
},

 woohoo i found it!here's how to a dropdown if you need to change the author of a document:

creatorId: {
type: String,
optional: true,
canRead: ['guests'],
editableBy:['admins'],
control:'select',
query: `
users{
results{
_id
username
}
}
`,
options:props=>
props.data.users.results &&
props.data.users.results.map(user=>({
value:user._id,
label:user.username
})),
resolveAs: {
fieldName: 'creator',
type: 'User',
resolver: (movie, args, context) =>
movie.creatorId && Meteor.users.findOne({ _id: movie.creatorId }),
addOriginalField:true
}
},

I am using creatorId instead of userId now..

  • first I use the query to get all users (i dont think you need to nest the query in results , something i copied from docs: https://docs.vulcanjs.org/forms.html#Field-Specific-Data-Loading)
  • the results of the query are accessed in the options (necessary for the 'select' control)
  • resolveAs tells it to resolve the id as a type of User, so we can access the user's name and other fields (I'm not sure if using Meteor.users.findOne is the best way to do that though