2016-12-21 11 views
0

別のエラーはありませんが、私はちょっとひとつ知りたいのですが。ユーザースキーマオブジェクトの参照を使用する方法_id意味location_id新しいユーザーを追加するときの使い方。nodejsで参照を与えるオブジェクトIDの使用方法mongodb

ユーザー・スキーマ:

var userSchema = Mongoose.Schema({ 

     name:{type: String,require:true}, 
     surname: {type: String,require:true}, 
     tel: {type: String,require:true}, 
     age: {type: String,require:true}, 
     mevki_id: {type: String,require:true}, 
     location_id: { type: Mongoose.Schema.Types.ObjectId, ref: 'locations' } 
}); 

場所スキーマ:

var LocationSchema = Mongoose.Schema ({   


    il: {type: String, require:true}, 

    ilce: {type:String, require:true}   

}); 

UserControllerで - 私はここで

this.createUser = function(req, res) { 

    var la=new Location({il:'istanbul',ilce:'camlica',location_id:la._id}).save(function (err) { 
     if (err) return handleError(err); 
    }); 

    var user = new User({ 
     name:'akif',surname:'demirezen',tel:'544525',age:'45',mevki_id:'2', 

    }).save(function (err) { 
     if (err) return handleError(err); 
    res.send(JSON.stringify(job)); 
    }); 

} 

答えて

0

あなたのコード内のいくつかの誤りがあり、ユーザーを追加します。たとえば、requireプロパティはrequiredである必要があります。

その他の問題は、laのlocation_id値をlaに設定していて、その時点でまだ値が割り当てられていないことです。

Mongoはすべてのオブジェクトに_id:ObjectIdというフィールドを自動的に作成します。これを試してみてください:

this.createUser = function(req, res) { 

    var la = new Location({ 
    il:'istanbul', 
    ilce:'camlica', 
    }).save(function (err, location) { 
    if (err) return handleError(err); 

    var user = new User({ 
     name:'akif', 
     surname:'demirezen', 
     tel:'544525', 
     age:'45', 
     mevki_id:'2', 
     location_id: location._id 
    }).save(function (err, user) { 
     if (err) return handleError(err); 
     // Warning: AFAIK job does not exist, should it be user? 
     res.send(JSON.stringify(job)); 
    }); 
    }); 
} 
+0

私は本当に私がこのres.send(JSON.stringify(user))になると思います。 – MAD

関連する問題