2013-02-19 4 views
5

사용자 모델과 연관성이있는 몽구스 모델을 가지고 있습니다.모델 매개 변수를 몽구스 모델로 전달

var exampleSchema = mongoose.Schema({ 
    name: String, 
    <some more fields> 
    userId: { type:mongoose.Schema.Types.ObjectId, ref: 'User' } 
}); 

var Example = mongoose.model('Example', userSchema) 

나는 새로운 모델을 인스턴스화 할 때 내가 할 :

// the user json object is populated by some middleware 
var model = new Example({ name: 'example', .... , userId: req.user._id }); 

모델의 생성자 때 스키마 변경을 작성하고 리팩토링 지루한되었다 매개 변수를 많이 걸립니다. 같은 일을 방법이 :

var model = new Example(req.body, { userId: req.user._id }); 

또는 요청 본체에 사용자 ID를 첨부 심지어 JSON 객체를 생성하거나하는 도우미 메서드를 만들 수있는 가장 좋은 방법은? 아니면 제가 생각조차하지 못한 방법이 있습니까? 당신이 req.body에 사용자 ID 복사 할 경우

답변

7
_ = require("underscore") 

var model = new Example(_.extend({ userId: req.user._id }, req.body)) 

가 나 : 또한

// We "copy" the request body to not modify the original one 
var example = Object.create(req.body); 

// Now we add to this the user id 
example.userId = req.user._id; 

// And finally... 
var model = new Example(example); 

: 내가 제대로 이해하면

var model = new Example(_.extend(req.body, { userId: req.user._id })) 
2

, 당신은 다음과 같은 노력하고 좋은거야 스키마 옵션에{ strict: true }을 추가하는 것을 잊지 마십시오. 그렇지 않으면 원치 않는/공격자 데이터를 저장할 수 있습니다.

+4

기본적으로 mongoose 3 이후 strict가 사용 설정됩니다. –

+0

팁을 제공해 주셔서 감사합니다. – gustavohenke

+0

'Object.create'는'req.body'를 복사하지 않으므로 여기에 맞는 것처럼 보이지 않으므로 프로토 타입 객체로 사용합니다. 확실히 Mongoose는 프로토 타입의 속성을 무시합니다. – JohnnyHK

관련 문제