[英]One-To-Many relation in MongoDB
目前,我正在查看mongoDB。 我嘗試使用nodejs和mongoose實現一個簡單的一對多關系:
模型/架構用戶:
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var UserSchema = new Schema({
name: String
});
module.exports = mongoose.model('User', UserSchema);
模型/架構文章:
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var ArticleSchema = new Schema({
name: {
type: String,
required: true
},
user: {
type: Schema.ObjectId,
ref: 'User'
}
});
module.exports = mongoose.model('Article', ArticleSchema);
所以,我現在的問題是:如何獲得所有用戶,包括其文章? 我真的也必須向我的UserScheme添加引用嗎? 這樣的一對多關系中的最佳實踐是什么? mongodb中是否有類似join的東西?
一個用戶有很多文章-一篇文章屬於一個用戶。 調用類似/ user /:user_id之類的東西,我想接收包含_id = user_id且包含其所有文章的用戶。
由於種種原因,這是最可怕的想法。
首先,BSON文檔大小限制為16MB。 您根本無法在文檔中添加更多內容。 與“一對多”關系相比,嵌入文檔更適合“一對(很少)”關系。
至於用例:您在這里有什么問題? 它是
對於給定的用戶,文章是什么?
在REST方面,僅應在/users/:id/articles
被獲取時返回文章,並且應將文章(僅文章)作為JSON數組返回。
因此,您的模型似乎很自然。 對於用戶:
{
_id: theObjectId,
username: someString
…
}
文章應如下所示:
{
_id: articleIdOrSlugOrWhatever,
authors: [theObjectId],
// or author: theObjectId
retention: someISODate,
published: someOtherISODate
}
因此,當為/users/:id
調用REST服務時,您只需查找
var user = db.users.findOne({_id:id})
當/users/:id/articles
被調用時,您將進行查找
var articles = db.articles.find({author:id})
遵循REST原則,以可擴展的方式解決問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.