NodeJS Mongoose将对象推入对象引用数组

时间:2018-09-03 12:03:23

标签: node.js mongodb object mongoose reference

这是我正在使用的架构:

var skillSchema = new mongoose.Schema({
    skill_name: String
});

var Skill = mongoose.model("Skill", skillSchema);

var userSchema = new mongoose.Schema({
    name: String,
    role: String,
    age: Number,
    skills: [
        {
            type: mongoose.Schema.Types.ObjectId,
            ref: "Skill"
        }
    ]
});

var User = mongoose.model("User", userSchema);

这是通过邮递员传递以创建具有技能的用户的JSON数据。

{
    "name" : "Name of user",
    "role" : "Developer",
    "age" : 20,
    "skills" :
    [
        {
            "skill_name" : "Skill name 1"
        },
        {
            "skill_name" : "Skill name 2"
        }
    ]
}

我无法将Skill对象推入User对象。 这是成功创建用户和技能但无法将技能推入用户的代码。

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

        User.create({
            name: req.body.name,
            role: req.body.role,
            age: req.body.age
        }, function(err, user){
            if (err) {
                console.log(err);
            } else {

                var skillsArray = req.body.skills;
                for (var i = 0; i <= skillsArray.length; i++) {
                    Skill.create(skillsArray[i],
                    function(err, skill) {
                        if (err) {
                            console.log(err);
                        } else {
                            console.log(skill)
                            user.skills.push(skill);
                        }
                    });
                }
                user.save(function(err, data) {
                    if (err) {
                        console.log(err);
                    } else {
                        res.json({status: 200, message: "User Created!", _id: data._id});
                        console.log("User Created");
                        console.log(user)        
                    }
                });

            }
        });

});

请帮助。预先感谢!

0 个答案:

没有答案