2016-11-03 6 views
-3

두 개의 콜렉션 인 "Person"과 "Stories"가 있습니다. Stories Model에는 restricted라는 필드가 있습니다. 사람 스키마에 제한이없는 이야기의 ObjectId를 저장해야합니다. 일반적으로 그 사람에게 가능한 이야기를 보여줍니다.Mongoose 다른 컬렉션의 ObjectId 참조를 저장 중입니다.

person.model.js

var mongoose = require('mongoose'), Schema = mongoose.Schema; 
var personSchema = Schema({ 
    name : String, 
    stories : [{ type: Schema.Types.ObjectId, ref: 'Story' }] 
}); 
var Person = mongoose.model('Person', personSchema); 

story.model.js

var mongoose = require('mongoose'), Schema = mongoose.Schema; var 
storySchema = Schema({ 
creator : String, 
title : String, 
restrictions : Boolean 
}); 
var Story = mongoose.model('Story', storySchema); 

나는 평균의 새로운 완성입니다. 먼저 제한되지 않습니다 이야기가있는 고유 한 ID의 목록을 얻을 수있는 날 person.controller.js

+1

"도와주세요"대개 여기에 대답을받지 않습니다. 문제에 직면 한 특정 질문을하고 초기 노력을 보여주십시오. – qqilihq

+0

은 사람 모델에 스토리의 오브젝트 ID를 저장해야합니다. 도움 외에도 제 질문은 분명하다고 생각했습니다. –

+1

[ask]와 [mcve]를 참조하십시오. – Mat

답변

1

에 쓸 찾을 도와주세요, 당신은 distinct() 명령을 사용하여이 작업을 수행.

당신이 다음 findByIdAndUpdate() 또는 findOneAndUpdate() 또는 update()을 사용하여 해당 목록과 함께 사람 모형의 이야기 필드를 업데이트 할 수 있습니다 ID의 목록을 얻을 때.

예는 다음과 같습니다

Story.distinct("_id", { "restrictions": false }).exec(function(err, stories) { 
    if (err) throw err; 
    Person.findByIdAndUpdate(personId, 
     { "$addToSet": { "stories": { "$each": stories } } }, 
     { "new": true }, 
     function(err, person) { 
      if (err) throw err; 
      console.log(JSON.stringify(person.stories, null, 4)); 
     } 
    ) 
}) 
+0

mongo에 데이터를 저장하는 나쁜 방법을 언급하고 있습니까? –

+0

이는 애플리케이션 디자인에 따라 달라지며 폭 넓은 주제입니다. MongoDB의 데이터 모델링에 대한 자세한 내용은 docs [Data Modeling Introduction] (http://docs.mongodb.org/manual/core/data-modeling-introduction/), 특히 [모델 일대 다 관계 임베디드 문서 포함] (http://docs.mongodb.org/manual/tutorial/model-embedded-one-to-many-relationships-between-documents/)을 참조하십시오. 그 외에도 위의 답변으로 문제가 해결 되었습니까? – chridam

+0

예 위의 답변은 내 문제를 해결했습니다. 감사 –

관련 문제