Loopback ValidationError: The `Role` instance is not valid. Details: `name` already exists (value: “admin”)

限于喜欢 提交于 2019-12-10 19:19:12

问题


I`m too new to loopback, however i followed the steps to install and scaffold my folder (loopback-server), inside server/boot/ i created one file script.js and included the following code:

    module.exports = function(app) {
var MongoDB = app.dataSources.MongoDB;

MongoDB.automigrate('Customer', function(err) {
   if (err) throw (err);
   var Customer = app.models.Customer;

   Customer.create([
    {username: 'admin', email: 'admin@admin.com', password: 'abcdef'},
    {username: 'user', email: 'muppala@ust.hk', password: 'abcdef'}
  ], function(err, users) {
    if (err) throw (err);
     var Role = app.models.Role;
    var RoleMapping = app.models.RoleMapping;

    //create the admin role
    Role.create({
      name: 'admin'
    }, function(err, role) {
      if (err) throw (err);
       //make admin
      role.principals.create({
        principalType: RoleMapping.USER,
        principalId: users[0].id
      }, function(err, principal) {
        if (err) throw (err);
      });
    });
  });
});

};

now im getting this error:

if you require more files let me know in comments below please, but i commented this file out and didnt get that error. by the way, i tried to change the keys and values of {username: 'admin',..} and Role.create({ name: 'admin'},.... but either doesnt work or it works but i cant login as admin.. it is too confusing for me. anybody can help please?

thank you.


回答1:


If you're Role entity is being stored in a database then this code would try to create that Role entity (with a name of "admin") each time your application starts. However, after the first time, that Role would already exist, thus you get an error that you have a duplicate "name". What you might want to do is check that the Role does not already exist, or not store the Roles in your DB.

You could add some code to check the current DB and only add that Role if it doesn't exist. Something like this:

Role.find({ name: 'admin' }, function(err, results) {
    if (err) { /* handle this! */ }

    if (results.length < 1) {
        // now we know the DB doesn't have it already, so do the Role creation...
    }
});

Note that you would also want to check if that Role table already has the principals you're adding and only add them if they aren't already there.



来源:https://stackoverflow.com/questions/39488730/loopback-validationerror-the-role-instance-is-not-valid-details-name-alre

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!