javascript - 两个模型: Post and Tag, 如何使用Mongoose建立多对多关系?

标签 javascript node.js mongodb mongoose

我目前有两个模型:Post 和 Tag。

这是帖子模型:

'use strict';

import mongoose from 'mongoose';

let PostSchema = new mongoose.Schema({
  url_path: {
    type: String,
    required: true,
    trim: true,
  },
  title: {
    type: String,
    required: true,
    trim: true,
  },
  body: {
    type: String,
    required: true,
    trim: true,
  },
  user_id: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User',
    required: true,
  },
  tags: [{
    tag_id: mongoose.Schema.Types.ObjectId,
    text: String,
  }],
  date_created: {
    type: Date,
    required: true,
    trim: true,
  },
  date_modified: {
    type: Date,
    required: true,
    trim: true,
  },
});

module.exports = mongoose.model('Post', PostSchema);

和标签模型:

'use strict';

import mongoose from 'mongoose';

let TagSchema = new mongoose.Schema({
  text: {
    type: String,
    required: true,
    unique: true,
    lowercase: true,
    trim: true,
  },
});

module.exports = mongoose.model('Tag', TagSchema);

我的最终目标是能够向路由发送 get 请求,其中路由的一部分是给定标签的 _id(例如:/tag/:tag_id/posts),并获取带有该标签的所有帖子的列表。

我不相信我会以最好的方式做到这一点(我是 Mongoose 的新手),但目前我能够向路由(/posts/:post_id/tags)发送发布请求并向帖子添加标签(如果标签尚不作为标签模型的实例存在,则创建标签)

这里是标签 Controller ,它处理标签的创建以及向帖子添加任何标签

'use strict';

import Tag from './../models/Tag';
import Post from './../models/Post';

module.exports.create = (req, res) => {
  Tag.findOne({
    text: req.body.text,
  })
  .then(tag => {
    if (tag === null) {
      let newtag = new Tag({
        text: req.body.text,
      });
      newtag.save();

      return newtag;
    } else {
      return tag;
    }
  })
  .then(tag => {
    Post.findById(req.params.post_id)
    .then(post => {
      post.tags.push(tag);
      post.save();

      res.json({
        post: post,
      });
    });
  });
};

module.exports.list = (req, res) => {
  Post.findById(req.params.post_id)
  .then(post => {
    res.json({
      post_tags: post.tags,
    });
  });
};

module.exports.getPosts = (req, res) => {
  let tagtext;
  let tagID;

  Tag.findById(req.params.tag_id)
  .then(tag => {
    if (tag === null) {
      res.send('no posts');
    } else {
      tagID = tag._id;
      tagtext = tag.text;
    }
  });

  Post.find({
    'tags._id': tagID,
  })
  .then(posts => {
    res.json({
      posts: posts,
    });
  });
};

最佳答案

module.exports.getPostsWithTag = (req, res) => {
    Post.find({ tags.tag_id: req.params.tag_id }, ...);
}

基于这篇文章的信息Find document with array that contains a specific value

关于javascript - 两个模型: Post and Tag, 如何使用Mongoose建立多对多关系?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34275871/

相关文章:

javascript - 如何确保我不会将内容替换为旧响应?

javascript - Node.js 中显示的 utf-8 字符不正确,如何解决?

ruby-on-rails - 使用mongoid更改rails 3应用程序中的id/URL slug

c# - Mongodb 数组元素匹配

Javascript正则表达式捕获组中的单词和分隔符

javascript - jQuery 事件中的三元运算符

javascript - 使用javascript动态创建div水平布局元素

javascript - 删除在 DFS 算法 cytoscape JS 中发现的边缘

node.js - Angular + Electron - 找不到模块 main.js

regex - 使用 PHP 进行整数值的 MongoDB 正则表达式搜索