引用架构

时间:2019-08-17 04:09:35

标签: node.js mongodb mongoose mongoose-schema mongoose-populate

我正在尝试将学生信息引用到用户架构。对于用户架构,我使用本地护照进行身份验证。我正在尝试使每个用户的用户信息都是唯一的,以及它与包含名称和其他详细信息的学生信息的联系。我尝试注册用户,然后通过ID查找它,并使用学生模式填充它。现在它没有显示任何错误,但是当我查看数据库中的用户时,学生信息未连接到该用户。请帮助

User Schema
var mongoose = require("mongoose");
var uniqueValidator = require('mongoose-unique-validator');
var passportLocalMongoose = require("passport-local-mongoose");

var UserSchema = new mongoose.Schema({
    username: String,
    password: String,
    usersInfo: {
            type: mongoose.Schema.Types.ObjectId,
            ref: 'StudentInfo'
        }
});
UserSchema.plugin(uniqueValidator);
UserSchema.plugin(passportLocalMongoose);

module.exports = mongoose.model("User", UserSchema);

Student Info Schema
var mongoose = require("mongoose");
var uniqueValidator = require('mongoose-unique-validator');
var passportLocalMongoose = require("passport-local-mongoose");

var StudentSchema = new mongoose.Schema({
    first_name: String,
    middle_name: String,
    last_name: String,
    street: String,
    town: String,
    city: String,
    region: String,
    country: String,
    studentId: String,
    day: Number,
    month: String,
    year: Number,
});

module.exports = mongoose.model("StudentInfo", StudentSchema);

my routes for both the create student infos and register users

var StudentInfo      = require("./models/studentInfo"),
    User      = require("./models/user");

app.post('/signup', function(req,res){

    StudentInfo.create(req.body.studentInfo, function(err, newlycreated){
        if(err) {
            res.redirect('back');
        }
        else {
            res.redirect('/register');
        }
   });
});

app.post('/register', function(req, res) {
    var user = {username: req.body.username};

    User.register(user, req.body.password, function(err, user){

        if(err) {
            console.log(err);
            res.redirect('back');
               }
        else {
            //console.log(user._id);
            User.findById(user._id).populate('StudentInfo').exec(function(err, found) {
            if(err) {
                console.log(err);
                res.redirect('back');
                    }
            else {
                 //console.log(User.studentInfo.first_name);
                 res.redirect('/');

            }

            });
        }
    });
});

1 个答案:

答案 0 :(得分:0)

请参阅docs

  

填充是使用其他集合中的文档自动替换文档中指定路径的过程。

因此,您需要指定路径,而不是集合名称。以下应该可以工作:

User.findById(user._id).populate('usersInfo')...