我开始使用mongo,我想为用户“喜欢的”项创建一个模式。我目前使用mongoose和node.js编写的代码如下:

// 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 db设计方法?如果没有,有人能告诉我什么是符合设计理念的东西吗?

最佳答案

是的,您是对的,关系设计方法和nosql设计方法完全不同。
例如,在RDBMS中有10个表,在Mongo中只能有2个或3个集合。这是因为我们在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);

关于node.js - 使用MongoDB和Mongoose构建收藏列表?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38668256/

10-11 06:56