2016-11-01 2 views
0

테이블 사용자가 있습니다. 이것은 스키마입니다.mongoDB 오브젝트 내에 고유 한 자동 증가 ID를 추가하는 방법

var usersSchema = mongoose.Schema({ 
    uname : {type : String , unique: true}, 
    email : {type : String}, 
    logintype : {type : String}, 
    password : String, 
    status : String, 
    hash : String, 
    social: {}, 
    games: Object, 
    os: String, 
    friends: Object, 
    msges:Object 
}); 

msges는 개체입니다. 하지만 내가 원하는 것은 msges 내부에 키 값 쌍이 있어야한다는 것입니다. 그래서 내가 한 것은

function sendMsgToFriend(uname,friendUname,title,msg,time,callback){ 
    global.users.find({"uname":friendUname}, 
    function(err,doc){ 
     if(err){ 
      callback(false,err,"Msg cannot be sent"); 
     }else{ 
      global.users.update({"uname" : uname}, 
      { 
       $addToSet : { 
       "msges":{time:{"from":uname,"title":title,"msg":msg,"read":false}} 
       } 
      },function(err,doc){ 
       if(err){ 
        callback(false,err,"Msg cannot be sent"); 
       }else{ 
        callback(true,null,"Msg has been sent"); 
       } 
      } 
     ); 
     } 
    } 
); 
} 

나는 '시간'키를 만들고 그 값을 휴식을 시도했다. 그러나 시간의 가치 대신에 "시간"이라는 문자열이 나타났습니다. 자동 증분 키를 만들 수 있습니까? 미리 감사드립니다.

답변

1

당신은 객체로 "MSG를"를 정의하지만 난 당신의 질문에서 읽은 것을 당신은 객체의 배열을 원하는됩니다 ..

왜 당신이 메시지에 대한 모델을 만들고 메이크업 "MSG를"을하지 않는 배열을 해당 개체에 대한 참조 메시지

var messageSchema = Schema({ 
    from : String, 
    title: String, 
    msg : String, 
    send_on : Date 
}); 

var Message = mongoose.model('Message', messageSchema); 

모든 메시지 모음에 있고 당신이 사용자 당 읽기 상태를 추적 할 수 있습니다이 방법에 대한

var usersSchema = mongoose.Schema({ 
    uname : {type : String , unique: true}, 
    email : {type : String}, 
    logintype : {type : String}, 
    password : String, 
    status : String, 
    hash : String, 
    social: {}, 
    games: Object, 
    os: String, 
    friends: Object, 
    msges: [{ 
     message_id : { type: Schema.Types.ObjectId, ref: 'Message' }, 
     read_on : Boolean }] 
}); 

및 스키마. 당신이 엑스트라의 컬렉션처럼 사용자 스키마 일을하지 않으려는 경우 : 당신이 mongoose populate

UPDATE 사용할 수 retriaval 사용자 중에 메시지를 검색

var usersSchema = mongoose.Schema({ 
     uname : {type : String , unique: true}, 
     email : {type : String}, 
     logintype : {type : String}, 
     password : String, 
     status : String, 
     hash : String, 
     social: {}, 
     games: Object, 
     os: String, 
     friends: Object, 
     msges: [{ 
      id : Schema.Types.ObjectId, 
      from : String, 
      title: String, 
      msg : String, 
      send_on : Date, 
      read_on : Boolean }] 
    }); 

그러나 명심 메시지를 보낸 사람에게 메시지를 보내려면 양쪽 사용자가 배열에 넣어야합니다 (동일하게 유지하십시오) .... 그래서 시나리오에서 가장 좋은 솔루션에 대해 생각하고 이야기해야합니다.

+0

나는 그것도 생각했지만 다른 테이블을 원하지 않습니다. 그들은 그것 안에 그것이 중첩되기를 원한다. –

+0

다른 컬렉션을 얻지 못하도록 사용자 테이블에 스키마를 포함 할 수도 있습니다. – HoefMeistert

+0

좀 더 간단하게 할 수 있습니까? 이 첫 번째 프로젝트입니다 : ( –

관련 문제