2017-05-22 1 views
1

나는 GET 요청을하는 입력에 위치를 입력하여 특정 도시의 날씨를 얻고 로그인 할 수있는 날씨 앱을 구축하고 있습니다. OpenWeatherMap API 사용자가 홈페이지 날씨로 조회 한 위치를 설정할 수있는 기능을 내장했습니다. 내 추론은 사용자 모델에서 "위치"라는 속성을 지정하고 사용자가 "홈페이지 날씨로 설정"을 클릭 할 때마다 업데이트합니다. 패치 요청을 만들기 위해 AJAX를 사용하려고 시도하지만 요청에 성공 함수가 실행 되더라도 모델은 업데이트되지 않습니다. 사용자 API에AJAX는 Node + Express에서 "패치"요청을하지 않습니다.

// app/models/user.js 
// load the things we need 
var mongoose = require('mongoose'); 
var bcrypt = require('bcrypt-nodejs'); 

// define the schema for our user model 
var userSchema = mongoose.Schema({ 


    email  : String, 
    password  : String, 
    location  : String, 


}); 

// methods 
// generating a hash 
userSchema.methods.generateHash = function(password) { 
    return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null); 
}; 

// checking if password is valid 
userSchema.methods.validPassword = function(password) { 
return bcrypt.compareSync(password, this.password); 
}; 

// create the model for users and expose it to our app 
module.exports = mongoose.model('User', userSchema); 

경로 :

router.route('/users/:id') 
    .get(userController.show) 
    .patch(userController.update) 

및 업데이트 방법 다음

var userId = $('.set-weather').attr('data-id') 
$(document).on('click', '.location-btn', function(){ 
    console.log(setLocation) 
    var data = { 
     location: setLocation 
    } 
    console.log("https://stackoverflow.com/users/" + userId) 
    $.ajax({ 
     url: '/users/' + userId, 
     method: 'patch', 
     dataType: "json", 
     data: ({location: data}), 
     success: function(result){ 
     console.log("Success") 
     }, 
     error: function(result){ 
     console.log("failure") 
     } 
    }) 
    }) 

는 노드와를 사용하여 익스프레스 사용자 모델 : 여기

내 AJAX 요청입니다 컨트롤러에서 :

01 23,

답변

0

업데이트합니다 컨트롤러 업데이트 방법이처럼

:

controller.update = function(req, res){ 
    var id = req.params.id; 
    var location = req.body.location; 
    User.findOneAndUpdate(
    {_id: id}, 
    { 
     location: location 
    }, 
    function(err, user){ 
     if(err){ 
     throw err; 
     } 
     res.json(user) 
    } 
    ) 
} 

은 기본적으로 문제가 당신의 URL PARAM로 id를 내보내지만, 그것은에서 사용할 수 있도록 패치 방법 위치를 보내고있다 req.body 대신 req.params

+0

@ Ian Springer이 솔루션이 효과가 있습니까? –

관련 문제