2017-04-02 5 views
1

나는, 다른 곳에 내가 전달 개체에 따라 일부 필드를 채 웁니다 몽구스 모델에 대한 방법을 쓸몽구스 모델 방법 : 속성을 저장하지 않습니까? .

let mySchema = mongoose.Schema({ 
    name: String, 
    age: Number, 
    street: { type: String, default: 'No' } 
}); 

mySchema.methods.populate = function(o) { 
    this.age = o.age + 10; 
}); 

을 시도하고 난 인스턴스를 초기화하고 방법을 실행하겠습니다 :

let newThing = new MySchema(); 
newThing.populate({ age: 12 }); 
newThing.save(); 

이렇게하면 기본 거리 이름 이외의 속성없이 mongo에 새 개체가 성공적으로 저장됩니다. 내가 뭔가 잘못하고 있는거야?

+0

스키마를 내보내시겠습니까? 코드에 다른 오류가 없기 때문입니다. – Khurram

+0

@Khurram 그가 스키마를 내 보내지 않으면 기본값을 저장 할 수 있습니까? – Tolsee

답변

1

작동하는이 코드를 참조 할 수 있습니다. model.js

var mongoose = require('mongoose') 
var Schema = mongoose.Schema 

const customSchema = new Schema({ 
    name: String, 
    age: Number, 
    street: { type: String, default: 'No' } 
}) 

// Custom function 
customSchema.methods.populate = function(o) { 
    this.age = o.age 
    return this.age 
} 

// create the model to export 
var custom = mongoose.model('customModel', customSchema) 

module.exports = custom 

먼저

에서 server.js

var mongoose = require('mongoose') 
    var Model = require('./model') 

    mongoose.Promise = global.Promise; 
    mongoose.connect('**dbUrl**') 

    var NewData = new Model({ 
     name: 'Tolsee' 
    }) 

    NewData.populate({ age: 15 }) 

    NewData.save(function(err){ 
     if (err) { 
      throw err 
     }else{ 
      console.log('Your data is saved successfully') 
     } 
    }) 

는, 당신은 스키마를 사용하기 위해 모델을 만들어야합니다. 이 모델의 인스턴스는 정의한 사용자 정의 메소드를 사용할 수있는 문서입니다.

관련 문제