2017-10-04 36 views
1

所以我爲我的應用程序佈局如下:演員貓鼬文檔其他同類型號

  1. UserSchema(包含用戶名和密碼)(在用戶鑑別())

    var UserSchema = new mongoose.Schema({ 
    firstName: String, 
    lastName: String, 
    email: String, 
    username: String, 
    password: String 
    }, options); 
    UserSchema.plugin(passportLocalMongoose); 
    
    module.exports = mongoose.model("User", UserSchema); 
    
  2. StudentSchema附加字段

    var StudentSchema = new mongoose.Schema({ 
    indexNumber: String, 
    courses: [{ 
        id: { 
         type: mongoose.Schema.Types.ObjectId, 
         ref: "Course" 
        }, 
        entryDate: { 
         type: Date, 
         default: Date.now 
        } 
    }] 
    }, options); 
    module.exports = User.discriminator("Student", StudentSchema); 
    
  3. TeacherSchema(discriminator()o N個用戶)與附加字段

    var TeacherSchema = new mongoose.Schema({ 
    degree: String, 
    courses: [{ 
        type: mongoose.Schema.Types.ObjectId, 
        ref: "Course" 
    }] 
    }, options); 
    module.exports = User.discriminator("Teacher", TeacherSchema); 
    

我使用的護照本地策略,User.register()。

router.post("/register", function(req,res) { 
var newUser = new User({ 
    firstName: req.body.firstName, 
    lastName: req.body.lastName, 
    email: req.body.email, 
    username: req.body.username 
}); 
User.register(newUser, req.body.password, function(err, user) { 
    if(err) throw err; 
    passport.authenticate("local")(req, res, function() { 
     req.flash("success", "Welcome " + user.username + "."); 
     res.redirect("/"); 
    }); 
}); 
}); 

現在,這一切都是相同的集合下用戶在DB(因爲鑑別)

如何,一個用戶註冊後,「提升」他的學生或老師,所以我可以有他的對象中的那些額外的領域?

回答

0

嘗試在用戶模型上使用update命令將「__t」設置爲「Teacher」或「Student」。我覺得默認的鑑別關鍵是__t,所以你需要這樣的東西:

user.update({$set: {__t: "Student" } }, callback)` 

然後,你需要鑑別把它再次得到您的領域:

const Student = User.discriminator("Student", StudentSchema); 
Student.findById(id, callback)