2016-07-29 60 views
0

我开始使用mongo,并且我想为用户'喜好'的项目创建一个模式。我当前的代码,用猫鼬和Node.js的看着如下:使用MongoDB和Mongoose构建收藏夹列表?

// load the things we need 
var mongoose = require('mongoose'); 

// define the schema for our favourites model 
var favouritedItemsSchema = mongoose.Schema({ 
    userId   : Number, 
    item    : [{ 
     itemId  : Number, 
     addedDate : Date 
    }] 
}); 

// create the model for favourites and expose it to our app 
module.exports = mongoose.model('Favourites', favouritedItemsSchema); 

从关系数据库背景的人,我想知道上述做法是否会代表一个合适的NoSQL数据库设计方法?如果没有,有人能告诉我什么是符合设计理念的东西吗?

回答

1

是的,你说得对,关系型和NoSQL设计方法完全不同。

例如在RDBMS中有10个表格,你可能只有2或3个mongo集合。这是因为我们在NoSQL(子文档,数组等等)中创建对象之间的关系更有趣。

下面是针对您的问题的一种解决方案,重用现有的用户集合。

// load the things we need 
var mongoose = require('mongoose'); 

// define the schema for our model 
var userSchema = mongoose.Schema({ 
    username: string, 
    favourites: [{ 
     id: Schema.Types.ObjectId, 
     addedDate: Date 
    }] 
}); 

// export model 
module.exports = mongoose.model('User', userSchema); 
+0

你还应该提到这样做是一种糟糕的做法,因为你创建了一个无约束的收藏数组,而不受约束的数组在mongo / –