使用MongoDB和Mongoose构建收藏列表?

时间:2021-05-29 23:35:06

I am starting to use mongo, and I would like to create a schema for items that a user has 'favourited'. My current code, using mongoose and node.js looks at follows:

我开始使用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);

Coming from a relational DB background, I am wondering whether the above approach would represent a suitable NoSQL DB design approach? If not, can someone show me what would be something that fits the design philosophy?

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

1 个解决方案

#1


1  

Yes, you are right, the relational and the NoSQL design approach are totally different.

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

Where you have 10 tables for example in RDBMS, you could have only 2 or 3 collections in mongo. That's because the way we create relations between objects is far more interesting in NoSQL (subdocument, arrays, etc..).

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

Here is one solution for your problem, reusing an existing User collection.

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

// 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);

#1


1  

Yes, you are right, the relational and the NoSQL design approach are totally different.

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

Where you have 10 tables for example in RDBMS, you could have only 2 or 3 collections in mongo. That's because the way we create relations between objects is far more interesting in NoSQL (subdocument, arrays, etc..).

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

Here is one solution for your problem, reusing an existing User collection.

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

// 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);