【发布时间】:2014-09-27 20:32:29
【问题描述】:
我正在学习猫鼬。目前我做了一些好事,但我真的不明白 Mongoose 如何管理 Schema 之间的关系。
所以,简单的事情(我希望):我正在做一个经典的练习(我自己做的,因为我找不到创建超过 2 个模式的好教程),其中包含 3 个模式:
用户、帖子、评论。
- 用户可以创建多个帖子;
- 用户可以创建多个评论;
- 帖子属于用户。
- 评论属于用户和帖子。
我不认为这是一件很难的事情吗?
目前我可以很好地管理用户和帖子之间的关系。我的单元测试返回的正是我所需要的,目前我正在使用mongo-relation,但我不知道这是否是个好主意......
it('Use should create a Post', function(done) {
User.findOne({ email: 'test@email.com' }, function(err, user) {
var post = {
title: 'Post title',
message: 'Post message',
comments: []
};
user.posts.create(post, function(err, user, post) {
if (err) return done(err);
user.posts[0].should.equal(post._id);
post.author.should.equal(user._id);
// etc...
done();
});
});
});
现在的问题是创建评论。 我无法创建同时引用帖子和用户的评论。
我做了类似的事情并且可以工作,但是当我执行 remove 时,它只会从帖子中删除,而不是从用户中删除。
所以我觉得有些东西我错过了,或者我仍然需要学习来增强它。
it('User should add a Comment to a Post', function(done) {
User.findOne({ email: 'test@email.com' }, function(err, user) {
if (err) return done(err);
var comment = new Comment({
author: user._id,
message: 'Post comment'
});
Post.findOne({ title: 'Post title'}, function(err, post) {
if (err) return done(err);
post.comments.append(comment, function(err, comment) {
if (err) return done(err);
post.save(function(err) {
if (err) return done(err);
});
comment.author.should.equal(user._id);
post.comments.should.have.length(1);
// etc...
done();
});
});
});
});
如您所见,代码不是很“好看”,但在创作方面效果很好。
问题是当我删除评论时。好像有什么不对。
这是模型关系:
// User Schema
var userSchema = new mongoose.Schema({
// [...],
posts: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Post' }],
comments: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Comment' }],
});
// Post Schema
var postSchema = new mongoose.Schema({
author: { type: mongoose.Schema.ObjectId, ref: 'User', refPath: 'posts' },
title: String,
message: String,
comments: [{ type: mongoose.Schema.ObjectId, ref: 'Comment' }]
});
// Comment Schema
var commentSchema = new mongoose.Schema({
author: { type: mongoose.Schema.ObjectId, ref: 'User', refPath: 'comments' },
post: { type: mongoose.Schema.ObjectId, ref: 'Post', refPath: 'comments' },
message: String
});
我真的希望在你的帮助下理解这一切。
如果有一个简单的关于它的教程也会很好。
【问题讨论】:
-
你如何删除它?
标签: javascript node.js mongodb express mongoose