I currently have two models: Post and Tag.
Here is the post model:
'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);
and the tag model:
'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);
My end goal is to be able to send a get request, to a route where part of the route is the _id of a given tag (for ex: /tag/:tag_id/posts), and get back a list of all the posts with that tag.
I don't believe I am going about doing this in the best possible manner (I am new to mongoose) but currently I am able to send a post request to a route (/posts/:post_id/tags) and add a tag to the post (which creates the tag if the tag doesn't already exist as an instance of the Tag model)
Here is the tag controller which handles the creation of the tag, and the addition of any tags to posts
'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,
});
});
};