Using Multiple schema for single Collection in Mongodb not Working - node.js

I want to use more than one schema for a single collection in mongodb but it doesn't stores except single schema. other schema only stores _id & _v what is wrong in my code ?
I have tried to follow
http://mongoosejs.com/docs/api.html#index_Mongoose-model
My schema model
const mongoose = require('mongoose');
const config = require('../config/database');
var Schema = mongoose.Schema;
// Reading content Schema
const contentArticle = new Schema({
contentCategory: { type: String },
contentTitle: { type: String },
body: { type: String },
});
// Quiz Content
const quizAllArticle = new Schema({
quizCategory: { type: String },
question: { type: String },
ans: { type: String }
});
// Article Schema
const topicSchema = new Schema({
artId: { type: String },
postURL: { type: String },
date: { type: Date, default: Date.now },
author: { type: String },
published: {type: String },
category: { type: String },
QuesPapType :{ type: String },
});
const Content = module.exports = mongoose.model('Contents', contentArticle, 'articles');
const Quiz = module.exports = mongoose.model('Quizs', quizAllArticle, 'articles');
const Topic = module.exports = mongoose.model('TopicContent', topicSchema, 'articles');
and other code is :
const express = require('express');
const router = express.Router();
const passport = require('passport');
const config = require('../config/database');
const Content = require('../models/art');
const Quiz = require('../models/art');
const Topic = require('../models/art');
router.post('/register',(req, res, next) => {
let topic= new Topic({
artId : req.body.artId,
author : req.body.author,
date : req.body.date,
published : req.body.published,
postURL : req.body.postURL,
category : req.body.pscCategory,
QuesPapType : req.body.QuesPapType,
});
console.log(topic);
topic.save(function(err) {
if (err) {
res.json({
success: false,
msg: 'failed to register'
})
} else {
res.json({
success: true,
msg: 'success to reg article'
})
}
})
});
router.post('/reg-content', (req,res,next) => {
let content= new Content({
contentCategory : req.body.contentCategory,
contentTitle : req.body.contentTitle,
body : req.body.body,
});
console.log(content);
content(function(err) {
if (err) {
res.json({success: false, msg: 'failed to register Content'})
} else {
res.json({success: true,msg: 'success to reg article'})
}
})
})
router.post('/reg-quiz', (req,res,next) => {
let quiz= new Quiz({
quizCategory : req.body.quizCategory,
question : req.body.question,
ans : req.body.ans,
});
console.log(quiz);
quiz.save(function(err) {
if (err) {
res.json({success: false,msg: 'failed to register Content'})
} else {
res.json({ success: true, msg: 'success to reg article'})
}
})
})
module.exports = router;
The main problem is that it saves to database from only one schema and other two schema saves only _id, date and _v

/* --------------------- models/art.js ------------------------------------*/
const mongoose = require('mongoose');
var Schema = mongoose.Schema;
// Reading content Schema
const contentArticle = new Schema({
contentCategory: { type: String },
contentTitle: { type: String },
body: { type: String },
});
// Quiz Content
const quizAllArticle = new Schema({
quizCategory: { type: String },
question: { type: String },
ans: { type: String }
});
// Article Schema
const topicSchema = new Schema({
artId: { type: String },
postURL: { type: String },
date: { type: Date, default: Date.now },
author: { type: String },
published: {type: String },
category: { type: String },
QuesPapType :{ type: String },
});
const Content = mongoose.model('Contents', contentArticle);
const Quiz = mongoose.model('Quizs', quizAllArticle);
const Topic = mongoose.model('TopicContent', topicSchema);
module.exports = {Content, Quiz, Topic};
/*--------------------routes/index.js ------------------------------------*/
var express = require('express');
var router = express.Router();
const {Content, Quiz, Topic} = require('../models/art.js');
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
router.post('/register',function(req, res, next) {
let topic= new Topic({
artId : req.body.artId,
author : req.body.author,
date : req.body.date,
published : req.body.published,
postURL : req.body.postURL,
category : req.body.pscCategory,
QuesPapType : req.body.QuesPapType,
});
console.log(topic);
topic.save(function(err) {
if (err) {
res.json({
success: false,
msg: 'failed to register'
})
} else {
res.json({
success: true,
msg: 'success to reg article'
})
}
});
});
router.post('/reg-content', function(req,res,next){
let content= new Content({
contentCategory : req.body.contentCategory,
contentTitle : req.body.contentTitle,
body : req.body.body,
});
console.log(content);
content(function(err) {
if (err) {
res.json({success: false, msg: 'failed to register Content'})
} else {
res.json({success: true,msg: 'success to reg article'})
}
})
});
router.post('/reg-quiz', function(req,res,next){
let quiz= new Quiz({
quizCategory : req.body.quizCategory,
question : req.body.question,
ans : req.body.ans,
});
console.log(quiz);
quiz.save(function(err) {
if (err) {
res.json({success: false,msg: 'failed to register Content'})
} else {
res.json({ success: true, msg: 'success to reg article'})
}
})
});
module.exports = router;

const Content = mongoose.model('Contents', contentArticle);
const Quiz = mongoose.model('Quizs', quizAllArticle);
const Topic = mongoose.model('TopicContent', topicSchema);
module.exports = {Content, Quiz, Topic};
//import
const {Content, Quiz, Topic} = require('your schema file');

Related

cant update in mongoDb with mongoose

I am trying to create a followers/following function in my project. However I cannot seem to update the DB correctly. I'm able to send the ids as they both print when I console.log but nothing in my DB updates and I do not get any response in my frontend.
route
app.put('/api/follow', async function (req, res, next){
const { id } = req.query;
const userFrom = req.body.data
console.log('OTHER USER ID',id)
console.log('CURRENT ID', userFrom)
User.findByIdAndUpdate(id), {
$push:{followers:req.body.data}
},{new:true},
(err,result)=>{
if(err) {
if(err) return res.status(400).send(err)
}
User.findByIdAndUpdate(req.body.data), {
$push:{following:id}
},{new:true}.then(result=> {
res.json(result)
}).catch(err=>{
return res.status(422).json({error:err})
})
}
})
user model
const mongoose = require("mongoose");
const User = mongoose.model(
"User",
new mongoose.Schema({
username: String,
email: String,
password: String,
phoneNo: String,
bio: String,
filePath: String,
following: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "User",
},
],
followers: {
type: mongoose.Schema.Types.ObjectId,
ref: "User",
},
})
);
module.exports = User;
my route end function
const clickHandler = () => {
const currentID = currentUser.id;
const id = this.props.id;
console.log('CURRENT ID',currentID)
console.log('otherUserID',id)
Axios.put(`http://localhost:8080/api/follow/?id=${id}`, { data: currentID }, { headers: authHeader() })
.then(response => {
if (response.data.success) {
console.log('FOLLOWED', response.data)
// this.setState({ userDetails: response.data.details })
} else {
alert('Error')
}
})
}
This should be
User.findByIdAndUpdate(id, {
You should not close the bracket after id but after new: true})

Tools to create a functional Shopping Cart

I'm creating an e-commerce using Reactjs for frontend and Nodejs for backend (also express), and i want to create an shopping cart "connected" to the user account, where the user can recharge the page, close it, and the cart doesn't reset.
I'm looking for tools to create this, or some tutorial to do it with node-express, thanks! (i don't have code yet, cause i don't know from where starts)
This is User Model with Cart( with add-to-cart and remove from cart Function )
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const userSchema = new Schema({
email: {
type: String,
required: true,
},
password: {
type: String,
required: true,
},
resetToken: String,
resetTokenExpiration: Date,
cart: {
items: [
{
productId: {
type: Schema.Types.ObjectId,
ref: "Product",
required: true,
},
quantity: {
type: Number,
required: true,
},
},
],
},
});
userSchema.methods.addToCart = function (product) {
const cartProductIndex = this.cart.items.findIndex((cp) => {
return cp.productId.toString() === product._id.toString();
});
let newQuantity = 1;
const updatedCartItems = [...this.cart.items];
if (cartProductIndex >= 0) {
newQuantity = this.cart.items[cartProductIndex].quantity + 1;
updatedCartItems[cartProductIndex].quantity = newQuantity;
} else {
updatedCartItems.push({
productId: product._id,
quantity: newQuantity,
});
}
const updatedCart = {
items: updatedCartItems,
};
this.cart = updatedCart;
return this.save();
};
userSchema.methods.removeFromCart = function (productId) {
const UpdatedCartItems = this.cart.items.filter((item) => {
return item.productId.toString() !== productId.toString();
});
this.cart.items = UpdatedCartItems;
return this.save();
};
userSchema.methods.clearCart = function () {
this.cart = { items: [] };
return this.save();
};
module.exports = mongoose.model("User", userSchema);
Here, Routes
router.get("/cart", (req, res, next) => {
req.user
.populate("cart.items.productId")
.then((user) => {
const products = user.cart.items;
// console.log(products);
res.render("home/cart", {
path: "/cart",
pageTitle: "Your cart",
products: products,
isAuthenticated: req.session.isLoggedIn,
});
// console.log(products);
})
.catch((err) => {
console.error(err);
});
});
router.post("/cart",(req, res, next) => {
const prodId = req.body.productId;
// console.log(prodId);
Product.findById(prodId)
.then((product) => {
return req.user.addToCart(product);
})
.then((result) => {
// console.log(result);
res.redirect("/cart");
});
});
Tech:-
Frontend:- Ejs View Engine
Backend:- Express, MongoDB Atlas

Data not inserting in DB

I'm facing this problem since couple of days where I'm trying to insert the data into mongodb using mongoose but not able to get the data in mongodb. Below is the schema that I have created
const mongoose = require('mongoose')
const db = require('../db/db')
const crypto = require('crypto')
const { v4 : uuidv4 } = require('uuid');
const validator = require('validator')
// const { stringify } = require('querystring')
const schema = mongoose.Schema
const userSchema = new schema({
ObjId: schema.Types.ObjectId,
name : {
type : String,
trim: true,
required : true,
maxlength: 32
},
email : {
type : String,
trim: true,
required : true,
validate(value) {
if(!validator.isEmail(value)){
throw new Error ('The Email you have entered is not correct. Please enter the correct Email ID')
}
}
},
hashed_password : {
type : String,
required : true,
},
about : {
type : String,
trim: true,
required: true
},
salt : String,
user_roles: {
type: Number,
default: 0,
required: true
},
history : {
type: Array,
default: []
},
// timestamps: {
// createdAt : '',
// updatedAt : {type : Date, default : Date.now()},
// },
}, {timestamps: true})
// added virtual field
userSchema.virtual('password')
.set((password) =>{
this.password = password,
this.salt = uuidv4()
this.hashed_password = this.encryptPassword(password)
})
.get(() => {
return this._password
})
userSchema.methods = {
encryptPassword : (password) => {
if(!password) return ''
try {
return crypto.createHmac('sha256', this.salt)
.update(password)
.digest("hex")
}
catch(error) {
if(error) {
console.log('Found an Error in Line 70 in User.Js', error.message)
}
}
}
}
module.exports = mongoose.model("User", userSchema);
This is how I'm connecting the db
const mongoose = require('mongoose')
require('dotenv').config
// const connectionURL = 'mongodb://127.0.0.1:27017'
//const databaseName = 'ecommerce_db'
mongoose.connect(
// connectionURL,
process.env.MONGOURI,
{
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true
}
)
// .then((result) => { console.log('Mongo DataBase Connected', result)})
.then(() => { console.log('Mongo DataBase Connected')})
.catch((err) => {console.log('Mongoose Connection Failed', err)})
and this is where I'm saving the data
const User = require('../models/user')
const { response } = require('express')
const mongoose = require('mongoose')
exports.signUp = (req, res) => {
console.log('[Logging]', req.body)
// const user = new User({
// _id: mongoose.Schema.Types.ObjectId(),
// name: req.body.name,
// email: req.body.email,
// password: req.body.hashed_password
// })
const user = new User(req.body)
user.save((error, response) => {
if(error) {
return res.status(400).json({
error
})
}
res.json({
user
})
})
}
I'm getting all the correct input and success messages but still I'm not able to get the data inside mongodb, am I doing something wrong

Updating a field in MondoDB

I am writing a multi-user online dictionary. I want to implement a leadership board, e.i. "score" attribute increases, as soon as a user adds a word. I have a rough idea on how to do it, and tried one solution, however it does not work. Could you please guide me?
Word API route
const express = require('express');
const router = express.Router();
const Word = require('../../models/Word');
const User = require('../../models/User');
const validateWordInput = require('../../validation/word');
const passport = require('passport');
// #route POST api/words
// #desc Add words to profile
// #access Private
router.post(
'/',
passport.authenticate('jwt', { session: false }),
(req, res) => {
const { errors, isValid } = validateWordInput(req.body);
// Check validation
if (!isValid) {
// Return any errors
return res.status(400).json(errors);
}
Word.find({}).then(word => {
if (
word.filter(
wrd =>
wrd.ugrWordCyr.toString().toLowerCase() ===
req.body.ugrWordCyr.toLowerCase()
).length !== 0
) {
return res
.status(404)
.json({ wordalreadyexists: 'Word already exists' });
} else {
const newWord = new Word({
user: req.user.id,
ugrWordCyr: req.body.ugrWordCyr,
rusTranslation: req.body.rusTranslation,
example: req.body.example,
exampleTranslation: req.body.exampleTranslation,
origin: req.body.origin,
sphere: req.body.sphere,
lexis: req.body.lexis,
grammar: req.body.grammar,
partOfSpeech: req.body.partOfSpeech,
style: req.body.style
});
newWord.save().then(word => res.json(word));
User.update(
{ _id: '5cf0cb78b3105d1ba8e30331' },
{ $inc: { score: 1 } }
);
}
});
}
);
User model
This is where a score attribute is located
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
// Create schema
const userSchema = new Schema({
name: {
type: String,
required: true
},
email: {
type: String,
required: true
},
password: {
type: String,
required: true
},
score: {
type: Number,
default: 0
},
avatar: {
type: String
},
date: {
type: Date,
default: Date.now
}
});
module.exports = User = mongoose.model('users', userSchema);
After successfully saving the word, we should update the user count
To update the respective user's score you can do the following:
newWord.save().then((word) => {
//now update user model
User.findOne({ _id: req.user.id }) <-- or an id you would like
.then((foundUser) => {
foundUser.score = foundUser.score + 1
foundUser.save()
.then((savedUser) => {
res.json({ word, savedUser })
})
.catch((err) => {
return res.status(400).json({ error: "could not add score"})
})
})
.catch((err) => {
return res.status(400).json({ error: "could not find user"})
})
})

Mongoose error in required properties

I'm connecting a Angular 2 app to MongoDB via Mongoose.
I'm trying to store some data, but i obtain an error on all required properties.
I set up a schema, serverside:
var mongoose = require("mongoose");
var Schema = mongoose.Schema;
var uniqueValidator = require("mongoose-unique-validator");
var schema = new Schema({
email: {
type: String,
required: true,
unique: true
},
password: {
type: String,
required: true
},
nome: {
type: String,
required: true
},
cognome: {
type: String,
required: true
},
dataNascita: {
type: Date
},
telefono: {
type: String
},
classifica: {
type: String
}
});
schema.plugin(uniqueValidator);
module.exports = mongoose.model("User", schema);
The user object is clearly filled:
Mongoose responds with an error:
Thanks in advance for any help.
Max
Update:
The call from a Angular service:
#Injectable()
export class AuthService {
constructor(private http: Http) {
}
addUser(utente: Utente) {
const body = JSON.stringify(utente);
return this.http.post('http://localhost:3000/utente', body)
.map((response: any) => {
console.log(response);
response.json();
})
.catch((error: Response) => Observable.throw(error.json()
));
}
}
The Moongose call:
var express = require('express');
var router = express.Router();
var User = require('../models/users');
router.post('/', function (req, res, next) {
var user = new User({
email: req.body.email,
password: req.body.password,
nome: req.body.nome,
cognome: req.body.cognome,
dataNascita: req.body.dataNascita,
telefono: req.body.telefono,
classifica: req.body.classifica
});
console.log(res);
user.save(function (err, result){
console.log(err);
console.log(res);
if (err){
return res.status(500).json({
titolo: "Errore durante il salvataggio",
errore: err
});
}
res.status(201).json({
messaggio: 'Utente salvato correttamente',
oggetto: res
});
});
});

Resources