How can I integrate MongoDB $addFields aggregation in the backend and frontend? - mongodb

React Front-end
// ADD CUSTOM FILED FUNCTION
const handleCustomFiled = () => {
const FieldContainer = document.querySelector(".custom-filed-container");
const input = document.createElement("input");
const label = document.createElement("label");
label.id = "custom-label";
label.innerText = "Custom Filed";
label.setAttribute("contenteditable", "true");
FieldContainer.appendChild(label);
FieldContainer.appendChild(input);
};
Backend code
const mongoose = require("../connection");
const Schema = mongoose.Schema;
const personSchema = new Schema({
firstName: String,
lastName: String,
birthDay: String,
gender: String,
pronouns: String,
relationship: String,
user: {
id: {
type: mongoose.Schema.Types.ObjectId,
ref: "User",
},
username: String,
},
});
module.exports = mongoose.model("Person", personSchema);

Related

Subdocument not being saved in its own collection - Mongoose

I found this on the documentation for mongoose:
Subdocuments have save and validate middleware just like top-level
documents. Calling save() on the parent document triggers the save()
middleware for all its subdocuments, and the same for validate()
middleware.
But that hasn't been working for me. when I call save on my parent, the subdocument doesn't get created in its own collection. Here's my code:
Cart Model
const mongoose = require("mongoose");
const cartSchema = new mongoose.Schema({
numOfSessions: {
type: Number,
required: true
},
status:{
type: String,
enum: ["completed", "active", "deleted"],
required: true
}
}, { timestamps: true, versionKey: false });
const Cart = mongoose.model('shoppingCart', cartSchema);
module.exports = Cart;
User Model
const mongoose = require("mongoose");
const Cart = require("./xxxx").schema
const Schema = mongoose.Schema;
const userSchema = new Schema({
firstName: {
type: String,
required: true
},
lastName: {
type: String,
required: true
},
password: {
type: String,
required: true,
},
email: {
type: String,
required: true,
unique: true
},
shoppingCarts: [ Cart ]
}, { timestamps: true, versionKey: false });
const User = mongoose.model('user', userSchema);
module.exports = User;
Server Side
const new_user = new User({
firstName: req.body.firstname,
lastName: req.body.lastname,
username: req.body.username,
phoneNum: req.body.phone,
userType: req.body.userType,
email: req.body.email,
password: hashedPassword
});
new_user.shoppingCarts.push(new_cart);
console.log('pushed')
new_cart.save(); //If i take out this line, this subdocument doesn't get saved
new_user.save()
.then((result) => {
console.log(result);
});
To save the subdocument, I'm having to call save on it them well. Is this how it's supposed to be? Thx :D

How to loop items in mongoose schema

I have mongoose Schema , where i have schemas by language. I want to loop them depend my other language model. Now I have them static(en, ru, ge).
const StrategyTranslatedFieldsSchema = mongoose.Schema(
{
title: String,
teaser: String
},
{ _id : false }
)
const StrategySchema = mongoose.Schema({
en: StrategyTranslatedFieldsSchema,
ge: StrategyTranslatedFieldsSchema,
ru: StrategyTranslatedFieldsSchema,
},
{
timestamps: true
});
my language schema:
const languageSchema = mongoose.Schema({
en:{
type: String,
default: 'en'
},
ru:{
type: String,
default: 'ru'
},
ge:{
type: String,
default: 'ge'
},
})
want something like that:
const mongoose = require('mongoose');
const slug = require('mongoose-slug-updater');
const Language = require('../models/Language')
mongoose.plugin(slug);
const StrategyTranslatedFieldsSchema = mongoose.Schema(
{
title: String,
teaser: String
},
{ _id : false }
)
const StrategySchema = mongoose.Schema({
slug: {
type: String,
slug: "en.title",
slugPaddingSize: 2,
unique: true
},
status:{
type: Boolean,
default: true
},
for(let key in Language){
key: StrategyTranslatedFieldsSchema
}
},
{
timestamps: true
});
const Strategy = mongoose.model('strategy', StrategySchema);
module.exports = Strategy;
Also interesting is it good practice to save multilingual data, like that example?
Thanks
You can do something like this.
// create object you want to pass StrategySchema
const strategySchemaObject = {
slug: {
type: String,
slug: "en.title",
slugPaddingSize: 2,
unique: true
},
status:{
type: Boolean,
default: true
}
}
// add each field to your schema object
Object.keys(Language.schema.obj).forEach((lang) => {
strategySchemaObject[lang] = StrategyTranslatedFieldsSchema
})
// create your schema
const StrategySchema = mongoose.Schema(strategySchemaObject, {
timestamps: true
})

MongoDB Mongoose Scheme Nested Document Structure and Relations

I have a project with the following document flow.
Users -> Accounts -> Projects
Users
Users have specific roles
Accounts
CRUD conditioned by User role
Specific users will have access to individual accounts. I was thinking to add an array userGroup with user id's?
Projects
Nested under Accounts related to a single accountToken ID
CRUD conditioned by User role
Specific users will have access to individual projects.
Here are example Schema models simplified for demo purposes.
UserSchema.js:
const UserSchema = new mongoose.Schema({
email: {
type: String,
required: [true, 'Please add an email'],
unique: true,
},
role: {
type: String,
enum: ['admin', 'user'],
default: 'user'
}
});
module.exports = mongoose.model('User', UserSchema);
AccountSchema.js:
const AccountSchema = new mongoose.Schema({
accountName: {
type: String,
},
accountToken: {
type: String
}
});
module.exports = mongoose.model('Account', AccountSchema);
ProjectSchema.js:
const ProjectSchema = new mongoose.Schema({
projectName: {
type: String,
},
projectType: String,
projectToken: String
})
module.exports = mongoose.model('Project', ProjectSchema);
I am stuck on the best way to setup nested or sub-document Schema Relations and the best way to relate the data between each other. Any guidance and suggestions would be a huge help! Thanks!!!
Try this;
const UserSchema = new mongoose.Schema({
email: {
type: String,
required: [true, 'Please add an email'],
unique: true,
},
role: {
type: String,
enum: ['admin', 'user'],
default: 'user'
}
});
module.exports = mongoose.model('User', UserSchema);
const AccountSchema = new mongoose.Schema({
userId: {
type: mongoose.Schema.Types.ObjectId,
required: true,
ref: 'User'
},
accountName: {
type: String,
},
accountToken: {
type: String
}
});
module.exports = mongoose.model('Account', AccountSchema);
const ProjectSchema = new mongoose.Schema({
accountTokenId:{
type: String
},
projectName: {
type: String,
},
projectType: String,
projectToken: String
})
module.exports = mongoose.model('Project', ProjectSchema);

missing values when saving model

When storing a new UserModel all that saves is
{ _id: 5d9e1ddf27c26e4aec7d3d20, __v: 0 }
Here is the Schema
const mongoose = require('../../db/index');
const bcrypt = require('bcryptjs');
const Schema = mongoose.Schema;
const OrganisationModel = require('../../models/organisations/index');
function hash(val) {
'use strict';
if (typeof val !== 'string') {
val = '';
}
var salt = bcrypt.genSaltSync(10);
var hash = bcrypt.hashSync(val, salt);
return hash;
}
const UserSchema = new Schema({
forename: {
type: String,
required: true
},
surname: {
type: String,
required: true
},
password: {
type: String,
required: true,
set: hash
},
email: {
type: String,
required: true,
unique: true
},
organisation: {
type: Schema.Types.ObjectId,
ref: OrganisationModel,
required: true
},
date: {
type: Date,
default: Date.now()
}
});
module.exports = UserSchema;
Here is the model
const mongoose = require('../../db/index');
const UserSchema = require('../../models/users/index');
const UserModel = mongoose.model('User', UserSchema);
module.exports = UserModel;
And here is the saving
const UserModel = require('../models/users/index');
const user = new UserModel({
forename: 'Tom',
surname: 'Kiernan',
password: 'test',
email: 'test#example.com',
organisation: '5d9e1a87cb220e7c64e7f8fb',
});
user.save(err => {
if( err ) {
console.log( err );
}
console.log( user );
});
Not specifically sure why it is only autogenerating the id and a version number what is happening to the rest of the info?
Also as you may notice in the code above I am error logging the save function and it is not returning any errors.
So I found my mistake because of a comment by #CuongLeNgoc
In model file I was requiring the model it's own file and trying to use it as the Schema.
Below is the updated file with notes
const mongoose = require('../../db/index');
// const UserSchema = require('../../models/users/index'); //Wrongly requiring the model again.
const UserSchema = require('../../schema/users/index'); // correctly requiring the schema
const UserModel = mongoose.model('User', UserSchema);
module.exports = UserModel;

Update mongodb document using discriminators

I've got a question about discriminators and mongoose/mongodb. I would like to understand how I can update one document which contains 2 properties whichs are array of discriminators.
Here my mongoose models :
const mongoose = require('mongoose');
const carSchema = require('./car');
const continentalWheelSchema = require('./wheel/continental');
const michelinWheelSchema = require('./wheel/michelin');
const CarSchema = new mongoose.Schema({}, { discriminatorKey: 'type', _id: false } );
const WheelSchema = new mongoose.Schema({}, { discriminatorKey: 'type', _id: false } );
const ClientParkSchema = new mongoose.Schema({
customer: { type: String, required: true },
created_at: { type: Date, default: Date.now },
updated_at: { type: Date, default: Date.now },
cars: [CarSchema],
wheels: [WheelSchema]
});
ClientParkSchema.path('cars').discriminator('break', carSchema);
ClientParkSchema.path('wheels').discriminator('continental', continentalWheelSchema);
ClientParkSchema.path('wheels').discriminator('michelin', michelinWheelSchema);
module.exports = {
ClientPark: mongoose.model('client_park', ClientParkSchema, 'client_park')
};
/////////////////////// CAR SCHEMA ////////////////////////
const mongoose = require('mongoose');
const CarSchema = new mongoose.Schema({
brand: { type: String, required: true },
model: { type: String, required: true },
}, { _id: false } );
module.exports = CarSchema;
/////////////////////// CONTINENTAL WHEEL SCHEMA ////////////////////////
const mongoose = require('mongoose');
const ContinentalWheelSchema = new mongoose.Schema({
model: { type: String, required: true }
}, { _id: false } );
module.exports = ContinentalWheelSchema;
/////////////////////// MICHELIN WHEEL SCHEMA ////////////////////////
const mongoose = require('mongoose');
const MichelinWheelSchema = new mongoose.Schema({
price: { type: number, required: true},
model: { type: String, required: true },
season: { type: String, required: true }
}, { _id: false } );
module.exports = MichelinWheelSchema;
mongodb query :
db.client_park.updateOne({_id: ObjectId('5d3865a4e56473518adabd35'), "car.type": 'break',"wheel.type": "michelin"}, {$set: {"car.$.brand": 'Ford',"wheel.$.price": 100,"wheel.$.season": "summer"}})
The query seems to work but the document is not updated. So I would like to know how could I update my document by discriminators (if there are exists).
Thank you very much !
EDIT :
The document I want to update :
{
"_id":"5d39a19e2376c7089ec7707b",
"customer":"5d0757aa4b6620003335aff2",
"cars":[
{
"type":"break",
"brand":"Ford"
}
],
"created_at":"2019-07-25T12:33:34.799Z",
"updated_at":"2019-07-25T12:33:34.799Z",
"_v":0
}