2016-09-09 33 views
-2

我正試圖在MongoDB中實現相關的數據概念。我有一個用戶集合和一個帖子集合。現在帖子集合已經被created_by引用了用戶集合。但是我無法檢索相關數據。以下是我的一些架構。Mongodb和Express

{ "posts" 
     { 
      created_by:{ type:mongoose.Schema.ObjectId, ref:'User'}, 
      created_at:{ type:Date,default:Date.now }, 
      text:String 
     } 
} 
{ 
     "users" 
     { 
      username:String, 
      password:String, 
      created_at:{type:Date,default:Date.now} 
     } 
} 
+0

嗨user3894192,歡迎來到Stack Overflow。你能否更詳細地描述你的意思是不能檢索相關數據?如果您可以向我們展示數據庫中數據的一些示例以及想要查詢的組合數據的示例,這將有所幫助。此外,您還需要顯示迄今爲止已嘗試過的內容,並描述哪些內容不起作用(例如,通過打印查詢輸出)。 –

+0

使用'mongoose'? – malix

回答

0

http://mongoosejs.com/docs/populate.html闡述了一個非常好的例子。我已經提取了這裏的要點

{ 
var personSchema = Schema({ 
    _id  : Number, 
    name : String, 
    age  : Number, 
    stories : [{ type: Schema.Types.ObjectId, ref: 'Story' }] 
}); 

var storySchema = Schema({ 
    _creator : { type: Number, ref: 'Person' }, 
    title : String, 
    fans  : [{ type: Number, ref: 'Person' }] 
}); 

var Story = mongoose.model('Story', storySchema); 
var Person = mongoose.model('Person', personSchema); 

} 

所以你現在有兩個模型的故事和故事通過_creator字段引用人的人。

現在填充_creator同時,通過故事,詢問您執行以下操作:

{ 

Story 
.findOne({ title: 'Once upon a timex.' }) 
.populate('_creator') 
.exec(function (err, story) { 
    if (err) return handleError(err); 
    console.log('The creator is %s', story._creator.name); 
    // prints "The creator is Aaron" 
}); 
} 

但你還需要確保你已經保存了正確的記錄,以便正確地檢索。同時節省您只需分配_id。見下文。

{ 
var aaron = new Person({ _id: 0, name: 'Aaron', age: 100 }); 

aaron.save(function (err) { 
    if (err) return handleError(err); 

    var story1 = new Story({ 
    title: "Once upon a timex.", 
    _creator: aaron._id // assign the _id from the person 
    }); 

    story1.save(function (err) { 
    if (err) return handleError(err); 
    // thats it! 
    }); 
}); 

} 
+0

你的答案解決了我的問題。謝謝。 – Shyam

+0

太棒了。很高興我能夠提供幫助。你能接受我的答案嗎? –

相關問題