2016-05-26 3 views
0

私は質問集を持っており、私は店舗モデルを持っています。私は、ストアモデルの質問フィールドを質問コレクションのオブジェクトIDの配列にする必要があります。私は後で人口を使用することができます。将来app.getを実行すると、ストア情報とすべての質問のあるドキュメントが表示されるはずです。文書を取り込む方法や参照を保存する方法

var Schema = mongoose.Schema; 

var storeSchema = Schema({ 
    name : {type : String}, 
    industry : {type : String}, 
    questions :[{type : Schema.Types.ObjectId, ref : "Questions" }] 
}) 

var questionsSchema = Schema({ 
    question : {type :String} 
}) 

var store = mongoose.model("Store", storeSchema); 
var questions = mongoose.model("Questions", questionsSchema) 

// questions.create({question: "question2"}, function(err,q){ 
//  console.log("create: " , q) 
// }) 
//something like this 
questions.find({}, function(err, doc){ 
    store.create({name : "store 1", industry : "industry 1" , questions : /*get the _ids from the question collection*/ {$push : doc.question}}) 
}) 


> db.questions.find().pretty() 
{ 
     "_id" : ObjectId("574534a289763c004643fa08"), 
     "question" : "question1", 
     "__v" : 0 
} 
{ 
     "_id" : ObjectId("574534acc90f3f2c0c3d529b"), 
     "question" : "question2", 
     "__v" : 0 
} 
> 
+0

@jack_blankあなたは、このためのソリューションを見つけましたか? –

答えて

0

人口とは、ドキュメント内の指定されたパスを他のコレクションのドキュメントに自動的に置き換えるプロセスです。 1つのドキュメント、複数のドキュメント、単純なオブジェクト、複数のプレーンなオブジェクト、またはクエリから返されたすべてのオブジェクトを読み込むことができます。

var question = new Questions(); 
    question.save(function(err) { 
     var store = new Store({ 
      name:'sample', 
      industry:'tech', 
      questions: [question._id], 
     }); 
     store.save(function(err){ 
     //do whatever you would like, post creation of store. 
     }); 
    }); 

    Store.find(...).exec(function(err, stores) { 
    Questions.populate(stores, function(err, storesPostPopulate) { 
     // Now you have Stores populated with all the questions. 
    }) 
    }); 

問題の質問フィールドは配列なので、別の質問IDを常にプッシュできます。

See mongoose populate

See mongoose Model populate

+0

あなたはそうすることはできません。 'question'を何かに設定しなければなりません。 Docは「refを保存する」と呼び出すので、それは私の問題です。私はそれをする方法を知らない。 –

+0

新しい店舗を保存せずに質問を追加するにはどうしたらいいですか?私が見るのは、あなたが店を保存する質問を保存するときだけです。私はそれをしたくありません。まだそれを取得しないでください。 –

+0

およびpopulateには文字列が必要です。 'TypeError:utils.populate:無効なパスです。期待される文字列。タイプ "関数" –

関連する問題