Wednesday, 3 May 2017

i want to use my token to search on my db(search specific user) then if user exists it updates UserProfile

i want to use my token to search on my db(search specific user) then if user exists it should update User profile(DB). I linked two schema's Users and UserProfile

USER SCHEMA 

    var userSchema = new mongoose.Schema({
        firstname: {type: String},
        lastname:{type:String},
        email: {type: String, unique:true},
        password: {type:String, required:true},
        gender:{type:String},
        resetPasswordToken:String,
        resetPasswordExpires:Date});
USER PROFILE SCHEMA

var userProfile = new mongoose.Schema({

    politics:{type:String},
    outdoor:{type:String},
    sports:{type:String},
    orientation:{type:String},
    talk:{type:String},
    description:{type:String},
    traits:[],
    User:[{
        type:Schema.Types.ObjectId,
        ref:'User'
    }],
})

//_id_new *** var _idnew = req.user // this comes from token acquired from response

models.User.findOne({_id:_idnew}, function (error, user) {
            if (error) {
                return next(error)
            }
            else {
                console.log("Data from update" + user)
                if (user) {

                    user.update(req.body, function (error, user) {
                        if (error) {
                            return next(error)
                        } else {
                            res.send(user)
                        }
                    })
                }

                else {

                    var newStuff = new models.UserProfile(req.body);
                    newStuff.save(req.body,function (error, user) {
                        if (error) {
                            return next(error)
                        } else {
                            return res.json({msg: "data updated ", user: user});
                        }
                    })
                }


            }
        })


via HackintoshSA

No comments:

Post a Comment