weblog schema design for Mongo database - database

I'm very new to Data base design
I'm going to design MongoDB data base for a weblog .
every post of blog will have comments .
now , we can design database in two approaches
Ffirst Approach
const postSchema = new mongoose.Schema(
{
title: {
required: true,
type: String
},
body: {
required: true,
type: String
},
comments: [{
required: true,
type: mongoose.Schema.Types.ObjectId,
ref: 'Comment'
}],
}
)
const commentSchema = new mongoose.Schema(
{
text: {
required: true,
type: String
}
}
)
As you see Coments in post model is Array of Comments
Second Approach
const postSchema = new mongoose.Schema(
{
title: {
required: true,
type: String
},
body: {
required: true,
type: String
},
}
)
const commentSchema = new mongoose.Schema(
{
text: {
required: true,
type: String
},
post_id: {
required: true,
type: mongoose.Schema.Types.ObjectId,
ref: 'Post'
},
}
)
As you can see ,there is user_id in comment schema .
the question is that
which schema model is correct ?
what are pros and cons of each schema ?

Related

How can I insert mongo changes in the deploy website?

My website is running allright and it's connected with Database.
I had to add more informations in my Mongo's collection. (I created the ActionPlanSchema).
import mongoose from "mongoose";
import mongoose_delete from "mongoose-delete";
const VerificationSchema = new mongoose.Schema({
text: { type: String, required: true },
});
const ActionPlanSchema = new mongoose.Schema({
title: { type: String, required: true },
mouraTitle: { type: String, required: true },
text: { type: String, required: true },
});
const RequirementSchema = new mongoose.Schema({
itemNumber: { type: String, required: true },
normPart: {
type: mongoose.Schema.Types.ObjectId,
ref: "NormPart",
required: true,
},
generalRequirement: {
type: mongoose.Schema.Types.ObjectId,
ref: "GeneralRequirement",
required: true,
},
specificRequirementDescription: { type: String, required: true },
subject: { type: mongoose.Schema.Types.ObjectId, ref: "Subject" },
criterion: String,
verification: [VerificationSchema],
actionPlan: [ActionPlanSchema],
});
RequirementSchema.index({ itemNumber: 1, normPart: 1 });
RequirementSchema.index({ specificRequirementDescription: 1 });
RequirementSchema.plugin(mongoose_delete, {
overrideMethods: "all",
deletedAt: true,
deletedBy: true,
indexFields: ["deleted"],
});
export default RequirementSchema;
And using a router in Postman (PUT method), I added some information to the Database ActionPlanSchema. Looking like that:
In my localhost, the actionPlan information it's showing. But when I do the deploy, the actionPlan gets undefined.
I believe that it's because the informations that I added in Postman weren't sent to the database used on the Deploy App.
How can I solve this problem? (I don't know if I could be very clear about my issue)
Anyway, thanks so much!

Advanced search with mongoose

I have an query object
const query = {
brand : BMW,
yearFrom : 2000,
yearTo : 2003,
price : 7000,
};
I am trying to find every BMW which is made between 2000 and 2003 included.
I am trying in this way but it doesn't work
if (query.yearFrom) {
return offerModel.find({query,year : {$gte : query.yearFrom }}, function(err,arr) {console.log(err,arr)}).skip(offset).limit(12);
}
Here's the mongoose schema
const mongoose = require('mongoose');
const offerSchema = new mongoose.Schema({
brand: {
type: String,
required: true,
},
model: {
type: String,
required: true,
},
year: {
type: Number,
required: true,
},
color: {
type: String,
required: true,
},
power: {
type: Number,
required: true,
},
mileage: {
type: Number,
required: true,
},
populatedState: {
type: String,
required: true,
},
price: {
type: Number,
required: true,
},
condition : {
type: String,
required: true,
},
doors: {
type: Number,
required: true,
},
description: {
type: String,
required: true,
},
transmission: {
type: String,
required: true,
},
engineType: {
type: String,
required: true,
},
category: {
type: String,
required: true,
},
imageURLs : [],
imageIds : [],
creator: {
type: mongoose.Types.ObjectId,
ref: 'user'
},
})
module.exports = mongoose.model('offers', offerSchema);
Sample data from database
_id:60fe98301b76642e04a31c45,
imageURLs:[],
imageIds : [],
brand:BMW,
model:335,
year:2000,
color:White,
doors:4,
power:130
mileage:30000,
populatedState:Sofia,
price:7000,
condition:Used,
description:qweqweqweqe,
transmission:Automatic gearbox,
engineType:Petrol,
category:Sedan,
creator:60fe97d11b76642e04a31c44,
__v:0,
If i put only query it find brand,model and etc.But it doesn't get year search correctly.
I will be glad if you guys have some ideas how can i fix that
Thanks !
Try this
offerModel.find({
$and: [
{ brand :query.brand },
year : {
$gte: query.yearTo,
$lt: query.yearFrom
}
]
}, function (err, results) {
...
}

Mongoose findByIdAndUpdate : can't update an array field

I'm new to mongoose and i have a problem.
In my app, i have a Travel model like this:
const travelSchema = new mongoose.Schema({
title: {
type: String,
required: [true, 'Please add a title'],
trim: true,
maxlength: [50, 'Title can not be more than 50 characters'],
},
cities: [
{
type: mongoose.Schema.Types.ObjectId,
ref: 'City',
},
],
});
and a City model like this :
const citySchema = new mongoose.Schema({
name: {
type: String,
required: true,
trim: true,
},
location: {
type: {
type: String,
enum: ['Point'],
required: true,
},
coordinates: {
type: [Number],
required: true,
},
},
travels: [
{
type: mongoose.Schema.Types.ObjectId,
ref: 'Travel',
},
],
});
So when i delete a travel, i want to remove the travel_id from the 'travels' field of the cities which are concerned by the travel.
Here i am:
exports.deleteTravel = asyncHandler(async (req, res, next) => {
const travel = await Travel.findByIdAndDelete(req.params.id);
travel.cities.map(cityId => {
City.findByIdAndUpdate(
cityId,
{ travels: travels.filter(id => id !== travel._id) },
{
new: true,
runValidators: true,
}
);
});
res.status(200).json({ success: true, data: {} });
});
I got this error message: Error: travels is not defined
Do you have any idea why?
Many thanks !
It's working like this :)
exports.deleteTravel = asyncHandler(async (req, res, next) => {
const travel = await Travel.findByIdAndDelete(req.params.id);
travel.cities.map(async cityId => {
await City.findByIdAndUpdate(
cityId,
{ $pull: { travels: travel._id } },
{
new: true,
runValidators: true,
}
);
});

Mongose array inside of array

I want to achieve like this:
On every user there's subject, and on every subject there's students.
user: [{ subjects: {subjectCode, description},[{students: {name, year, phone}}]}]
I already got the users -> subject side.
my problem now is how can i achieve to create students inside of subjects?
This is for my authentication.
User.js
const mongoose = require('mongoose');
const UserSchema = mongoose.Schema({
name: {
type: String,
required: true,
},
email: {
type: String,
required: true,
unique: true,
},
password: {
type: String,
required: true,
},
date: {
type: Date,
default: Date.now,
},
});
module.exports = mongoose.model('user', UserSchema);
Every user can create subjects.
Subject.js
const mongoose = require('mongoose');
const SubjectSchema = mongoose.Schema({
user: {
type: mongoose.Schema.Types.ObjectId,
ref: 'users',
},
student: [
{
type: mongoose.Schema.Types.ObjectId,
ref: 'student',
},
],
title: {
type: String,
required: true,
},
description: {
type: String,
},
date: {
type: Date,
default: Date.now,
},
});
module.exports = mongoose.model('subject', SubjectSchema);
In every subjects, there's should array of students.
Student.js
const mongoose = require('mongoose');
const StudentSchema = mongoose.Schema({
user: {
type: mongoose.Schema.Types.ObjectId,
ref: 'users',
},
name: {
type: String,
required: true,
},
year: {
type: String,
},
phone: {
type: String,
},
email: {
type: String,
required: true,
},
date: {
type: Date,
default: Date.now,
},
});
module.exports = mongoose.model('student', StudentSchema);

How to save nested array of objects data using mongoose?

So, I'm sending data from angular reactive form like:
Angular reactive form UI image
and
Data being sent to backend in browser console image
I have made schema for task as:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
let taskSchema = new Schema({
taskId:{
type:String,
unique:true
},
task:{
type:String,
default:''
},
subTask:[{
type: Schema.Types.ObjectId,
ref: 'SubTask'
}]
}
module.exports = mongoose.model('Task',taskSchema);
Schema for Sub-Task as:
let subTaskSchema = new Schema({
title:String,
subSubTask:[{
type: Schema.Types.ObjectId,
ref: 'SubSubTask'
}]
})
module.exports = mongoose.model('SubTask',subTaskSchema);
Schema for Sub-Sub-Task as:
let subSubTaskSchema = new Schema({
title:String
})
module.exports = mongoose.model('SubSubTask',subSubTaskSchema);
Now,I'm confused about how to save nested array of objects data in mongodb using mongoose?
you can define your schema like this
const userSchema = new mongoose.Schema({
likedBooks: [{
type: mongoose.Types.ObjectId,
ref: 'books'
}],
email: {
type: String,
required: true
},
name: {
type: String,
required: true
}
});
exports.User = mongoose.model('users', userSchema);
then you can populate data by doing
user = User.find({ email: req.body.email }).populate('likedBooks');
here likedBooks contains _id of each book
const bookSchema = new mongoose.Schema({
isbn: {
type: Number,
required: true
},
name: {
type: String,
required: true
},
author: {
type: String,
required: true
},
publisher: {
type: String,
default: ""
},
imageUrl: {
type: String,
required: true
},
description: {
type: String,
default: ""
}
});
exports.Book = mongoose.model('books', bookSchema);
for both schema i have not put _id as it is auto generated by mongodb and it is used as reference
The Object Model should look like this before saving.
{
taskId: 1,
task: 'Do something',
subTask: [{
title: 'Write a essay',
subSubTask: [{
title: 'Collect details to write an essay'
}]
}]
}
Hope it helps...

Resources