ES6 Node.js/Express.js模型对象的唯一主键 [英] Unique primary key for ES6 Node.js/Express.js Model Object
问题描述
在Node.js/Express.js应用中,需要对下面的ES6 AppUser
模型对象进行哪些具体更改,以使 name
主要键将始终是唯一的?
In a Node.js/Express.js app, what specific changes need to be made to the ES6 AppUser
model object below so that the name
primary key will always be unique?
作为上下文,该用户正在通过单独的OAuth2授权服务器进行身份验证,因此该特定客户端Node.js/Express.js应用程序永远不会在本地数据库中存储该用户的信息.因此, AppUser
实例将仅存在于内存中,并且将是有关用户的信息的临时持有者.我们不能依靠MongoDB这样的数据存储区来执行主键,因为用户不是本地持久存储的.
As context, the user is being authenticated by a separate OAuth2 authorization server, so this particular client Node.js/Express.js app will never store the user's information in a local database. Therefore, the AppUser
instance will exist only in memory, and will be a temporary holder of information about the user. We cannot rely on a datastore like MongoDB to enforce the primary key because the user is not locally persisted.
Here is the code for the appuser.js
file, which was added to the app/models
directory of this GitHub sample app for testing purposes:
'use strict';
module.exports = class AppUser {
constructor(name) {
this.name = name;
}
getName() {
return this.name;
}
getSomeOther() {
return this.someOther;
}
setSomeOther(other) {
this.someOther = other;
}
}
下面是一个代码示例,该示例在应用程序其他位置实例化 AppUser
的新实例:
And here is an example of code that instantiates a new instance of AppUser
elsewhere in the app:
var AppUser = require("./models/appuser.js");
...
var newUser = new AppUser(uname);
推荐答案
我建议找出香草的问题.如果您只想在应用程序执行期间检查名称是否唯一,则可以将用于实例化该类的名称存储在数组中
I propose to figure out the problem with vanillia. If you just want to check if name is unique during execution of the app, you could store names used for instanciation of the class in an array
'use strict';
var store = []
class AppUser {
constructor(name) {
if (store.indexOf(name) === -1) {
this.name = name;
store.push(name)
}
else {
console.log("warning " + name + " already exists");
return;
}
}
getName() {
return this.name;
}
}
var user1 = new AppUser("marco");
var user2 = new AppUser("raphaello");
var user3 = new AppUser("marco");
console.log(user2.getName());
run :
warning marco already exists
raphaello
当然,这只是一个主意,如果应该保留这个主意,则抛出异常将使实例化比我的返回更好
Of course it's just an idea, and if this idea would deserve to be remained, throwing an exception would be better to make the instanciation abort than my return
这篇关于ES6 Node.js/Express.js模型对象的唯一主键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!