how can i efficiently model my Mongoose Schema's? - javascript

Good Morning all! - i'll try to keep it short.
Coming from a begginers SQL/EF background i definitely went into mongoose with the wrong mindset.
I have 3 tables:
Users /
Boards /
BoardObjects
Now originally i thought about storing the boards as an array in the users document. But i think i'm approaching this wrong and i need community advice.
i need to be able to query what users what own what boards, and what objects are on those boards, and the arrays i put in were a nightmare. Then i thought, do i even need to cross these over?
for example, if i store a User, and then create a board, and in the board has a UserId that has to be unique to the user, and same for the BoardObjects, UserId and a BoardId, from what i've read so far seems it might be possible this way using joins and whatnot, which ive still got to learn..
Whats the community view here? do you embed or normalise often? or is this a valid way of managing related data in mongoose?
Providing Boards model for context
const Board = mongoose.model('Board', new mongoose.Schema({
Ownerid: {
type: mongoose.Schema.Types.ObjectId,
required: true,
ref: 'User'
},
name: {
type: String,
required: true,
minlength: 5,
maxlength: 50
},
datecreated: {
type: Date,
},
datemodified: {
type: Date
},
BoardObjects: [{ boardobjectid: { type: mongoose.Types.ObjectId, ref: 'BoardObject' } }],
}));

if i am understanding you correctly, you need to create a relationship between the two tables. in the user model you can add something like.
userSchema.virtual('boards', {
ref: 'Boards',
localField: '_id',
foreignField: 'owner'
});
then as part of your boards model build your relationship with the user as an object on the model like this.
owner:{
type: mongoose.Schema.Types.ObjectId,
required: true,
ref: 'User'
}
I hope this helps!

As per my knowledge,You can go with following answer as below:
const Board= new mongoose.Schema({
Ownerid: {
type: mongoose.Schema.Types.ObjectId,
required: true,
ref: 'User'
},
name: {
type: String,
required: true,
minlength: 5,
maxlength: 50
},
datecreated: {
type: Date,
},
datemodified: {
type: Date
}
})
const Board=mongoose.model('Board',userSchema)

Related

ObjectIDs in other collections without getting duplicate key error

I am getting the following error when trying to create a document in a collection.
MongoServerError: E11000 duplicate key error collection: stock-trading-system-db.trades index: user_id_1 dup key: { user_id: ObjectId('6266de71b90b594dab9037f3') }
Here is my schema:
const tradeSchema = new mongoose.Schema({
user_id: {
type: Schema.Types.ObjectId,
ref: 'User',
required: true
},
stock_id: {
type: Schema.Types.ObjectId,
ref: 'Stock',
required: true
},
stock_amount: {
type: Number,
required: true
},
stock_value: {
type: Number,
required: true
},
time_of_trade: {
type: Date,
required: true,
default: new Date()
},
trade_status: {
type: String,
enum: ['Approved', 'Declined', 'Pending'],
required: true,
default: 'Pending'
}
}, { collection: 'trades' })
I don't want user_id and stock_id to be unique, i just want it to check that those ObjectIDs exist in their respective collections before making the trade document. How do i achieve this?
It looks like a collection saves the schema that is defined in mongoose, and even if you change the schema, the unique values will stay the same inside the collection.
So even though i had removed
unique: true;
from my mongoose schema, it hadn't removed this from the collection in my DB.
Therefore the solution to this is to delete the collection and recreate it.

User, post, and comment model in mongoose

I am making a forum app that is quite similar to Reddit. I am using mongoose here for schema design. I have some doubts regarding models that I have- User, Post and Comment.
Does the schema look all right of all the models?
In User, I want to show the friends on the user profile. Like when you go to his profile, there will be like Friends(200), and when I click the friend list will appear(like Facebook, then on clicking you can access friends' profiles). I haven't created Friend schema, but does it needed actually?
Question about comments. So far, I have the basic comment schema. What happens to the threaded comments or replies. How do I store them?
All the models that I have currently:
const userSchema = new Schema(
{
username: { type: String, required: true },
email: { type: String, reuired: true },
password: { type: String, required: true },
country: { type: String, required: true },
friends: [{ type: Schema.Types.ObjectId, ref: "Friend" }], // is it needed?
posts: [{ type: Schema.Types.ObjectId, ref: "Post" }],
},
{ timestamps: true }
)
const postSchema = new Schema(
{
title: { type: String, required: true },
description: { type: String, required: true },
user: { type: Schema.Types.ObjectId, ref: "User" },
slug: { type: String, slug: "title" },
upvotes: { type: Number },
downvotes: { type: Number },
city: { type: String }, // post will have a tag by the city like NewYork, LA etc.
},
{ timestamps: true }
)
const commentSchema = new Schema(
{
comment: { type: String, required: true },
post: { type: Schema.Types.ObjectId, ref: "Post"},
user: { type: Schema.Types.ObjectId, ref: "User"},
upvotes: { type: Number },
downvotes: { type: Number }
},
{ timestamps: true }
)
For the Second Question you don't need friend schema since friend is also a user.
For the first question, Why do intend to store all the posts of a user inside the User object as a list of posts, this would mean fetching 100s of posts even when something basic like username or email is required. Instead, you can place user_id in the Post Schema, helping to identify posts from a particular User.

Mongoose schema update is not pick it up by Mongodb database

I've my db already created where I have the following schema:
const ProjectSchema = new mongoose.Schema({
name: { type: String },
description: { type: String },
client: {
type: mongoose.Schema.Types.ObjectId,
ref: 'client'
},
group: {
type: mongoose.Schema.Types.ObjectId,
ref: 'project_group'
}
});
I need to change the schema to
const ProjectSchema = new mongoose.Schema({
name: { type: String, unique: true, required: true },
description: { type: String },
client: {
type: mongoose.Schema.Types.ObjectId,
ref: 'client'
},
group: {
type: mongoose.Schema.Types.ObjectId,
ref: 'project_group'
}
});
because we need to force name to be unique and not null. After change this definition, I see that the db still saving documents with the same name value. My question is, how can I apply any change I've done in my schema? and, how can I do that automatically without doing this manually?
Regards
You most likely need to index that field so it can be quickly searched. Then also restart your server, if you haven't already. It's easy to do if you have MongoDB Compass (the official MongoDB GUI), or you can read this doc.
https://docs.mongodb.com/manual/core/index-single/#create-an-index-on-an-embedded-field

Sails.js with mongodb design

just starting out in sails.
Currently I have a User Model set up. I also have another Founder Model to store information specific to Users who are also Models.
attributes: {
companyName: {
type: 'string',
required: true
},
tagLine: {
type: 'string',
required: true
},
location: {
type: 'string',
required: true
},
market: {
type: 'string',
required: true
},
psName: {
type: 'string',
required: true
},
psDesc: {
type: 'string'.
required: true
}
}
So my question in the FounderController...would inputting the unique id for the user from User for the database be implemented in the models or in the controller? The Founder model will essentially create it's own unique id.
My first approach would to basically find the ID from the User documents, store it into a variable, update the Founder document's id field with the user id?
I felt this isn't very efficient. Thanks.

Sails.Js - Simple Exercise with 2 Relations on the ORM

I'm new to Sails.js and Node.js, so if i'm asking a simple question please forgive me.
I'm doing an API that must have a database, and i wanted to implement MySQL because i have some relations between tables. So i wrote the relational model by hand, like it is on the figure:
And i tried to implement is using sails.js, but for some reason i can't get the relation Level to Score working while the User-Score relationship is working fine.
Here are my models:
User.JS
module.exports = {
attributes: {
name:{
type:'string',
required: true
},
address:{
type: 'string'
},
email:{
type: 'string',
email:true,
unique: true,
required: true
},
encryptedPassword:{
type: 'string'
},
tranusertoscore:{
collection:'scores',
via: 'transcoretouser'
}
}
}
Level.js
module.exports = {
attributes: {
lvl_name:{
type: 'string',
required: true
},
tranleveltoscore:{
collection: 'scores',
via: 'transcoretolevels'
}
}
};
and finally
Score.js
module.exports = {
attributes: {
lvl:{
type: 'string',
required: true
},
score:{
type: 'integer',
required: true
},
transcoretouser:{
model: 'user'
},
transcoretolevels:{
model: 'level'
}
}
};
So, can you guys tell me what i'm doing wrong?
Sorry to take your time if the answer is easy, but i tried to follow documentation and search about the subject and didn't find any relevant answers.

Categories

Resources