-
Notifications
You must be signed in to change notification settings - Fork 0
/
user.js
65 lines (57 loc) · 1.48 KB
/
user.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
require('dotenv').config({path: __dirname + '/.env'})
var mongoose = require("mongoose")
mongoose.connect(process.env.MONGO_URI, { useNewUrlParser: true, useUnifiedTopology: true }, function(err){
console.log(err)
});
var Schema = mongoose.Schema;
const userSchema = new Schema({
username:{
require:true,
type:String
}
})
var User = mongoose.model("User", userSchema);
var findUserByUsername = function(username, done){
User.findOne({"username":username}, (err, user)=>{
if (err) console.log(err)
done(null, user)
})
}
var findUserById = function(id, done){
User.findOne({"_id": id}, (err, user) => {
if (err) console.log(err)
done(null, user)
})
}
var createUser = function(username, done){
var user = new User({"username":username})
findUserByUsername(username, (err, data)=>{
if (err) console.log(err)
if (data){
done(null, "taken")
} else {
user.save(function(err, data){
if (err) console.log(err);
done(null, data);
})
}
})
}
var listAllUsers = function(done){
User.find({}, function(err, users){
if (err) console.log(err)
var obj = {
userList:[]
}
users.forEach(function(user){
obj.userList.push(user);
})
done(null, obj)
})
}
module.exports = {
createUser,
findUserById,
findUserByUsername,
listAllUsers
}