【发布时间】:2019-02-20 10:45:47
【问题描述】:
我很好奇构建我的 mongoose Schema 的最佳方式是什么。我正在制作一个用户模式设置如下的电影网站:
let UserSchema = new mongoose.Schema({
username: {
type: String,
index: true
},
password: {
type: String
},
email: {
type: String
},
name: {
type: String
},
watchlist: [mongoose.Schema.Types.Mixed],
seen: {
like : {
type: [mongoose.Schema.Types.Mixed]
},
dislike: {
type: [mongoose.Schema.Types.Mixed]
}
},
});
当用户点击一个拇指向上或拇指向下图标时,一个对象
{movieID: movieID, title: movieTitle, poster: moviePoster}
将被发送到 seen 属性中的 like 或 dislike 数组。我将在我的 EJS 模板中使用此信息来确定电影是否已经看过,如果看过并喜欢,则将不喜欢按钮变灰,如果看过和不喜欢,则将喜欢按钮变灰。如果用户单击“清除”按钮,我还希望能够从看到的项目中删除该项目。为了做到这一点,似乎我将不得不遍历两个数组以确定电影是否包含在一个数组中,然后将其删除。似乎必须有更好的方法来做到这一点。我正在考虑使用movieID作为键来构造'seen'对象,如下所示:
seen: {
'123': {
movieID: '123',
title: 'movieA',
poster: 'movieA-poster.jpg',
like: true
},
'456' : {
movieID: '456',
title: 'movieB',
poster: 'movieB-poster.jpg',
like: false
}
}
但是当我尝试使用 .findOne 和这个函数发送数据时:
const movieObj = {
id: req.body.movieID,
title: req.body.movieTitle,
poster_path: req.body.poster_path,
};
User.findOne({_id: req.user._id}, function(err, user) {
if (err) {
console.log(err);
} else {
user.seen[req.body.movieID] = movieObj;
user.save(function(){});
}
}
我仍然只是得到一个空对象返回给我。我将架构看到的对象更改为:
seen: { type: mongoose.Schema.Types.Mixed, default: {} }
并设置了 {minimize: false},因为我读到猫鼬默认不允许空对象。感谢有关我做错了什么的任何指导,或者您是否有更好的方法来有效地构建架构以允许从数据库中轻松添加或删除看过的电影。
【问题讨论】:
-
帮助你的参考链接,如何使用填充:alexanderzeitler.com/articles/…
标签: node.js database mongodb mongoose database-design