Loopback ValidationError:"Role"实例无效.详细信息:“名称"已经存在(值:"admin") [英] Loopback ValidationError: The `Role` instance is not valid. Details: `name` already exists (value: "admin")
问题描述
我太新了,无法环回,但是我按照以下步骤在server/boot/内安装并搭建了我的文件夹(环回服务器),我创建了一个文件script.js,并包含以下代码:
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:
如果您需要更多文件,请在下面的评论中让我知道,但我对此文件进行了评论,但未收到该错误. 顺便说一句,我试图更改{username:'admin',..}和Role.create({ 名称:"admin"},.... 但是,要么不起作用,要么它起作用,但是我不能以管理员身份登录.对我来说,这太令人困惑了. 有人可以帮忙吗?
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?
谢谢.
推荐答案
如果您将Role
实体存储在数据库中,则此代码将尝试创建该Role实体(名称为"admin"
)每次您的应用程序启动时.但是,在第一次使用该角色后,该角色将已经存在,因此您将收到一个错误,指出您有一个重复的名称".您可能想要做的是检查角色是否不存在,或不将角色存储在数据库中.
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.
这篇关于Loopback ValidationError:"Role"实例无效.详细信息:“名称"已经存在(值:"admin")的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!