Data not inserting in DB - node.js

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

Related

How to waiting while document updating in mongoose?

I have this code:
module.exports = async (msg) => {
const postId = msg.wall.copyHistory[0].id;
const userId = msg.wall.ownerId;
const bonusePostManager = new BonusePostManager(postId)
const post = await bonusePostManager.getPost(postId);
if (!post) return;
if (post.reposters.includes(userId)) return;
const balanceManager = new BalanceManager(userId, 0);
const doubleCheckReposter = await bonusePostManager.getPost(postId);
if (doubleCheckReposter?.reposters.includes(userId)) return;
bonusePostManager.addReposter(userId)
.catch(console.error)
.then((res) => {
balanceManager.plusBalance(post.bonuseAmount, 'balance').then(async (res) => {
await messageAssistant.sendMessage({
peer_id: userId,
text: `Вы сделали репост, вы получаете ${numberWithSpace(post.bonuseAmount)}`
})
})
})}
If a person makes a repost from two devices at the same time, then the document does not have time to update and allows the possibility of a double repost. I tried using the $addToSet operator:
addReposter(userId, postId = this.postId) {
return Bonuse.updateOne({
id: postId,
}, {
$addToSet: {
'reposters': userId
}
})
}
But it doesn't help, I really don't know how to fix it. I return the promiss everywhere, try to wait for them, but this does not fix the situation, please help me!
I also attach the BonusePost scheme:
const { Schema } = require('mongoose');
const PostSchema = new Schema({
postId: {
type: Number,
unique: true,
index: true
},
active: {
type: Boolean,
default: true,
index: true,
},
bonuseAmount: {
type: Number,
},
reposters: {
type: Array,
default: [],
}
})
module.exports = PostSchema;
And model:
const { model } = require('mongoose');
const PostSchema = require('./schema');
const Bonuse = new model('Bonuse', PostSchema)
module.exports = Bonuse;

I want to upload images to my database using mongoose-gridfs. but i'm having trouble with that

I want to upload images using mongoose-gridfs. And I am having the following Problem (The one I show below in the photo). It is with the use of mongoose-gridfs and I would like if someone has worked with this library and in the way that I structure it below, it will help me to solve my situation or update me if there is a newer way to do it following this same structure. Thanks in advance.
This image show the error when i try to execute my code
Here my model Attachment
'use strict'
const mongoose = require('mongoose');
const gridfs = require('mongoose-gridfs')({ // TypeError: require(...) is not a function
collection: 'attachments',
model: 'Attachment'
});
const AttachmentSchema = gridfs.schema;
module.export = mongoose.model('Attachment', AttachmentSchema);
Here my model User where I pass Attachment as ref to the photo atributte
'use strict'
require('mongoose-type-email');
const bcrypt = require('bcrypt-nodejs');
const crypto = require('crypto');
const uniqueValidator = require('mongoose-unique-validator');
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const userSchema = new Schema({
first_name: {type: String, required: true},
email: {type: mongoose.SchemaTypes.Email, required: true, unique: true},
password: {type: String, required: true},
active: {type: Boolean, default: false},
created: {type: Date, default: Date.now()},
photo: {type: Schema.ObjectId, ref: "Attachment"},
valid_token: {type: String},
});
Now my fileService.js service that I use to upload the images.
'use strict'
const Attachment = require('../models/Attachment');
const im = require('imagemagick');
const fs = require('fs');
const events = require('events');
const gridfs = require('mongoose-gridfs')({ //TypeError: require(...) is not a function
collection: 'attachments',
model: 'Attachment'
});
exports.uploadFile = function (file, cb) {
const eventEmitter = new events.EventEmitter();
const lista = Object.values(file);
const properties = Object.getOwnPropertyNames(file);
const result = [];
const listLength = lista.length;
eventEmitter.once('err', err => {
cb(err);
});
eventEmitter.once('upload', lista => {
cb(null, lista);
});
eventEmitter.on('uploadFinish', (obj, property) => {
obj.contentType.startsWith("image") ? result.push({
type: 'img',
'property': property,
'value': obj
}) : result.push({type: 'video', 'property': property, 'value': obj})
if (listLength == result.length)
eventEmitter.emit("upload", result);
});
lista.length != 0 ? fileWrite(lista, properties, eventEmitter) : eventEmitter.emit("upload");
};
function fileWrite(lista, properties, eventEmitter) {
const files = Array();
const Attachment = gridfs.model;
lista.forEach((element, index) => {
Attachment.write({
filename: element.name,
contentType: element.type
},
fs.createReadStream(element.path),
(err, createdFile) => {
err ? eventEmitter.emit('err', err) : eventEmitter.emit('uploadFinish', createdFile,
properties[index]);
});
});
}
Here is my userService.js where I call the uploadFile function of the fileService.js service
'use strict'
const User = require('../models/User');
const fileService = require('../services/fileService');
exports.save = function (file, data, res) {
fileService.uploadFile(file, (err, files) => {
if (!err) {
if (files) {
files.forEach((e) => {
if (e.property == "photo") {
data.photo = e.value;
}
});
}
data['created'] = new Date();
const user = new User(data);
user.save((err, user) => {
if (!err) {
user.update(data, (error) => {
if (!error) {
res.json({success: true, message: "Inserted user", data: user})
} else {
res.send({
success: false,
message: 'User cant be updated'
});
}
});
} else
res.status(500).send({success: false, message: 'Error trying to save the user'});
});
} else {
res.status(500).send({success: false, message: 'Error trying to upload files'});
}
});
};
mongoose-gridfs specifies a different way of using it here:
const { createModel } = require('mongoose-gridfs');
etc.
See here for your specific error.

Result not getting stored in Google datastore DB

Not able to save the data in Google Datastore DB not getting any error, can somebody help me to find the fix
Console.log result as below
entityKey: Key { namespace: undefined, kind: 'User', path: [Getter] },
entityData:
{ firstname: 'Abcd',
lastname: 'Abcd',
email: 'abcd#gmail.com',
password: '123454',
createdOn: 'Abcd',
[Symbol(KEY)]: Key { namespace: undefined, kind: 'User', path: [Getter] } },
Ref - https://www.npmjs.com/package/gstore-node
const express = require('express');
const router = express.Router();
const { check, validationResult } = require('express-validator');
var User =require('../models/user');
//get register page
router.get('/register',function(req,res){
res.render('register')
});
//get login page
router.get('/login',function(req,res){
res.render('login')
});
router.post('/register', [
check('Name').isEmpty().withMessage('The Name is required'),
check('Email').isEmail().withMessage('Email is requried'),
//check('Password').isEmpty().withMessage('pass is requried'),
//check('Password','Password is Requried').isEmpty(),
// check('Password2','Password Not Match').equals('password2'),
], (req, res,next) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
res.render('register',{
error:errors.mapped()
})
}else{
console.log()
const newUser = new User ({
firstname:req.body.name,
lastname:req.body.name,
email :req.body.Email,
password :req.body.Password,
createdOn:req.body.name
});
console.log("Data1",newUser)
const createUser = (req, res) => {
const entityData = User.sanitize(req.body);
const user = new User(entityData);
console.log("Data2",createUser)
user.save()
.then((entity) => {
res.json(entity.plain());
})
.catch((err) => {
// If there are any validation error on the schema
// they will be in this error object
res.status(400).json(err);
})
};
req.flash('success_msg','you are registered and can login now');
res.redirect('/users/login');
}
});
module.exports=router;
const { Gstore, instances } = require('gstore-node');
const { Datastore } = require('#google-cloud/datastore');
const gstore = new Gstore();
const datastore = new Datastore({
projectId: 'sinuous250616',
});
gstore.connect(datastore);
// Save the gstore instance
instances.set('unique-id', gstore);
const bcrypt = require('bcrypt');
// Retrieve the gstore instance
const ggstore = instances.get('unique-id');
const { Schema } = ggstore;
/**
* A custom validation function for an embedded entity
*/
const validateAccessList = (value, validator) => {
if (!Array.isArray(value)) {
return false;
}
return value.some((item) => {
const isValidIp = !validator.isEmpty(item.ip) && validator.isIP(item.ip, 4);
const isValidHostname = !validator.isEmpty(item.hostname);
return isValidHostname && isValidIp;
});
}
//Create the schema for the User Model
const userSchema = new Schema({
firstname: { type: String, required: true },
lastname: { type: String, optional: true },
email: { type: String, validate: 'isEmail', required: true },
password: { type: String, read: false, required: true },
createdOn: { type: String, default: gstore.defaultValues.NOW, write: false, read: false }
});
/**
* List entities query shortcut
*/
const listSettings = {
limit: 15,
order: { property: 'lastname' }
};
userSchema.queries('list', listSettings);
/**
* Pre "save" middleware
* Each time the entity is saved or updated, if there is a password passed, it will be hashed
*/
function hashPassword() {
// scope *this* is the entity instance
const _this = this;
const password = this.password;
if (!password) {
return Promise.resolve();
}
return new Promise((resolve, reject) => {
bcrypt.genSalt(5, function onSalt(err, salt) {
if (err) {
return reject(err);
};
bcrypt.hash(password, salt, null, function onHash(err, hash) {
if (err) {
// reject will *not* save the entity
return reject(err);
};
_this.password = hash;
// resolve to go to next middleware or save method
return resolve();
});
});
});
// add the "pre" middleware to the save method
userSchema.pre('save', hashPassword);
/**
* Export the User Model
* It will generate "User" entity kind in the Datastore
*/
module.exports = gstore.model('User', userSchema);
*I think there is a problem with User model **
You should have a User model like this in /models/user.js (put models at the root of your application) to define User:
const { instances } = require('gstore-node');
const bscrypt = require('bcrypt-nodejs');
// Retrieve the gstore instance
const gstore = instances.get('unique-id');
const { Schema } = gstore;
var usersSchema = new Schema({
firstname:{type:String},
lastname:{type:String},
email:{type:String},
password :{type:String},
createdOn: Date
})
var User = gstore.model('User', usersSchema);
module.exports = User;
And you forgot to use to save with save()
var newUser = new User ({
firstname:req.body.name,
lastname:req.body.name,
email :req.body.Email,
password :req.body.Password,
createdOn: new Date() // there is a problem here.... use new Date()
});
newUser.save(); //<======= it is abscent so it won't save

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"})
})
})

Using Multiple schema for single Collection in Mongodb not Working

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');

Resources