考虑您将博客文章作为一个模型Post
,将标签作为另一个Tag
。任何帖子都可以有多个标签,类似地,任何标签都可以有多个帖子。
模型定义如下
Post.js
const mongoose = require("mongoose");
const Post = mongoose.model(
"Post",
new mongoose.Schema({
name: String,
content: String,
tags: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "Tag"
}
]
})
);
module.exports = Post;
Tag.js
const mongoose = require("mongoose");
const Tag = mongoose.model(
"Tag",
new mongoose.Schema({
name: String,
slug: String,
post: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "Post"
}
]
})
);
module.exports = Tag;
为了简化此操作,用户只能选择预先存在的标签。有一个选择name
和_id
填充。因此,当我们发布表单数据以创建新帖子时,我们可以按照以下步骤进行操作:
Post.create({
name: req.body.name,
content: req.body.content,
tags: req.body.tags
}).then(post => res.json(post));
})
req.body.tags
中的数据将是一个ObjectID数组。
如果我们要发布帖子,例如使用Post.findOne({ _id: req.params.postID }).popuplate('tags')
,我们将获取所有信息,包括标签信息。
但是,如果我们运行此命令Tag.findOne({ _id: req.params.tagID }).popuplate('posts')
,我们将不会得到我们刚刚添加的帖子,因为该帖子尚未添加到标签文档中。
这基本上是一个漫长的询问方式,我们如何将新创建的文档的ObjectID添加到子文档中?还是这完全是错误的方法?