How to craft Post requests for MEAN Stack? - javascript

I am currently programming a reminders app based on this project in an effort to learn JS and MEAN Stack. As part of my project, I am trying to add a date which each reminder is to be completed by. However, when using Postman to POST in a date, I am receiving an error message unless I cut the date field and only use JSON to put the reminder's title in. If I use Javascript for my POST, it greys out the title field in my POST's body and when I attempt to use JSON, the time field's entry is not recognized. The pertinent code is below. Any help is appreciated.
const express = require('express');
const app = express();
const mongoose = require('./db/mongoose');
const bodyParser = require('body-parser');
const {List, Reminder} = require('./db/models')
app.post('/lists/:listId/reminder', (req, res) => {//add a reminder to the specified list
let newReminder = new Reminder({
title: req.body.title,
_listId: req.params.listId,
time: req.body.time
});
newReminder.save().then((newReminderDoc) => {
res.send(newReminderDoc);
})
})
const mongoose = require('mongoose');
const ReminderSchema = new mongoose.Schema({
title:{
type: String,
required: true,
minlength: 1,
trim: true
},
_listId:{
type: mongoose.Types.ObjectId,
required: true
},
time:{
type: Date,
required: true
}
});
const Reminder = mongoose.model('Reminder', ReminderSchema);
module.exports = { Reminder }
JS Query I am trying to used:
{
title: "Test",
created: new Date("2016-12-12")
}

Related

Mongoose not saving data according to a function (discord.js)

Today, I decided to make a Discord RPG bot which of course requires profile stats such as coins and the actual users. Therefore, I searched up a tutorial on how I can do this with MongoDB but I am running into one issue. When a guild member joins and the bot is running, the data does not save with no error at all and I am unsure of why this is happening. I have tried troubleshooting the connection status by adding a line console.log(mongoose.connection.readyState) after the bot attempts to connect to the database. This returns 1 which means the connection is fine. I cannot find any other reason why this is caused so I decided to ask a question after hours of thinking.
(index.js): Connecting to the database
const mongoose = require("mongoose");
mongoose.connect(process.env.MONGO_SERVER, {
useNewUrlParser: true,
useUnifiedTopology: true
}).then(() => [
console.log("Connected to MongoDB Database successfully!"),
console.log(mongoose.connection.readyState)
]).catch((err) => {
console.error(err);
});
(profileSchema.js): Creating a profile schema
const mongoose = require("mongoose");
const profileSchema = new mongoose.Schema({
id: { type: String, require: true, unique: true },
serverid: { type: String, require: true },
coins: { type: Number, default: 0 },
bank: { type: Number }
});
const model = mongoose.model("ProfileModels", profileSchema);
module.exports = model;
(guildMemberAdd.js): Creating and uploading the data into the database
const profileModel = require('../models/profileSchema');
module.exports = async(client, discord, member) => {
let profile = await profileModel.create({
id: member.id,
serverid: member.guild.id,
coins: 0,
bank: 0
})
profile.save();
}
The reason is to do with the way you connect to mongo
BY default mongo closes the connection after connecting to a database. To do this, when connecting to mongo pass in the keepAlive option, so it would look something like:
mongoose.connect(process.env.MONGO_SERVER, {
useNewUrlParser: true,
useUnifiedTopology: true,
keepAlive: true
})
This will then mean an active connection to your database will be kept open
You are exporting 'model' from profileSchema.js and requiring 'profileModel ' from guildMemberAdd.js?
so import model from profileSchema and not profileModel
Fix: Make sure the guildMemberAdd event is being called by adding console.log statements.
If not, check if guildMemberAdd's code is different to other event codes.

React, MongoDB, Mongoose: How to format my date to be readable?

Using MERN-stack to build an app (MongoDB, ExpressJS, ReactJS, NodeJS)
I know there are plenty of docs/other solutions on stackoverflow for similar issues.
However, what confuses me about my scenario is that I'm not creating a new Date() object and then rendering it.
I have a backend model set up that has an attribute for Date, using Mongoose:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const UserSchema = new Schema({
username: {
type: String,
required: true,
unique: true
},
date: {
type: Date,
default: Date.now
}
})
module.exports = User = mongoose.model('user', UserSchema)
Now I'm simply rendering the user's data on a component/page but it comes out as
2020-05-10T17:57:14.987Z
You can use the moment library like so:
Documentation here
const myTime = moment(dateFromDB).format('hh:mm:ss') // or any other format

Node/ Express Rest API keeps entering same controller function inspite of correct mapping

I am writing a node/express rest api.
Hitting,
http://localhost:5000/api/news
and
http://localhost:5000/api/news/?id=c5f69d56be40e3b56e55d80
both give me all the news objects because it enters the same .getNews function on for both the urls.
My controller:
const NewsController = {};
const News = require('../models/news.model');
// This implementation of getNews is using Promises
NewsController.getNews = function(req, res) {
console.log('Inside getNews');
sendResponse = function(arg) {
res.json(arg);
}
const allnews = News.find({}, function(err, ns) {
sendResponse(ns);
});
};
// ES6 style
NewsController.getSingleNews = async (req, res) => {
console.log("Inside getSingleNews");
const news = await News.findById(req.params.id);
res.json[news];
};
NewsController.createNews = async (req, res) => {
const news = new News(req.body);
await news.save();
res.json[{
'status': 'item saved successfully'
}];
};
NewsController.deleteNews = async (req, res) => {
await News.findByIdAndRemove(req.params.id);
res.json[{
'status': 'item deleted successfully'
}]
};
module.exports = NewsController;
My routes.js (I am using the router at /api. So app.js has // use Router
app.use('/api', newsRoutes);
)
const express = require('express');
const router = express.Router();
var newsController = require('../controllers/NewsController')
router.get('/news', newsController.getNews);
router.get('/news/:id', newsController.getSingleNews);
router.post('/news', newsController.createNews);
router.delete('news/:id', newsController.deleteNews);
module.exports = router;
My Model
const mongoose = require('mongoose');
const { Schema } = mongoose;
const newsSchema = new Schema({
title: { type: String, required: true },
content: { type: String, required: true },
author: { type: String },
image: { type: String },
source: { type: String }
});
module.exports = mongoose.model('news', newsSchema);
The issue with your code is the way you are trying to call your endpoint. Express routes don't match query string parameters.
Having said that, your call to the news endpoint that looks like this:
http://localhost:5000/api/news/?id=c5f69d56be40e3b56e55d80
Should look like this instead:
http://localhost:5000/api/news/c5f69d56be40e3b56e55d80
That way the id parameter will get mapped to the req.params.id property inside your getSingleNews controller.
Being that the expected behavior for the way you declared your route:
router.get('/news/:id', newsController.getSingleNews);
For more information on how express routes work, check the documentation here: https://expressjs.com/en/guide/routing.html
Use /news/:id first. Your request will be redirected to the first matched url following the declaration order.
So /api/news satisfies app.get(/news)? Yep, gets redirected to that controller.
/api/news/?id=c5f69d56be40e3b56e55d80 satisfies app.get(/news)? Yep, also gets redirected to /news controller.
By the way, as your getting the id from req.params you should use /news/c5f69d56be40e3b56e55d80. If you were to get it from req.query you wouldn't need another route. /news?id=c5f69d56be40e3b56e55d80 would be perfect, you'd just need to check the existence of req.query.

"MissingSchemaError" when seeding database using mongoose-seeder

I am attempting to seed a database using mongoose-seeder, and I keep getting a MissingSchemaError. I am sure that I am setting up the schema properly, so I am lost as to why this is happening.
The file where I set up the schema looks like this:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const UserSchema = new Schema({
fullName: {
type: String,
required: true,
trim: true
},
emailAddress: {
type: String,
unique: true,
required: true,
match: /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)| .
(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-
Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
},
password: {
type: String,
required: true
}
});
const User = mongoose.model('User', UserSchema);
module.exports.User = User;
and in my main file:
'use strict';
// load modules
const morgan = require('morgan');
const mongoose = require('mongoose');
const seeder = require('mongoose-seeder');
const data = require('./data/data.json');
const express = require('express');
const app = express();
//set up database connection
mongoose.connect("mongodb://localhost:27017/courseapi");
const db = mongoose.connection;
//handle err connecting to db
db.on("error", (err) => console.error("Error connecting to database: ",
err));
//success
db.once("open", () => {
console.log("Connected to database");
seeder.seed(data, {dropDatabase: false}).then(function(dbData){
console.log("Database seeded!");
}).catch(function(err){
console.error("Error seeding database", err);
})
});
any help would be much appreciated!
The mongoose-seeder package is not maintained. Hence suggesting an alternative to import data. You can populate MongoDB in the CLI (command line interface) using mongoimport.It will load a JSON file into a specified MongoDB Instance & Collection. All you need is a mongod instance to be running before execution.
Please go through the walkthrough.
thank you for your help! The project required using a module to seed the data, so I ended up using mongoose-seed instead. (Required some reformatting of the json, but thankfully the file was relatively small)
it's better to use the actively maintained Seedgoose. It's the ultimate mongoose seeder with smart reference support.

Friend Based System in Node.js

So I currently have a real-time chat application up and running with node and socket.io. What I would like to do from here is let users create an account and search for other users based on their usernames. Then, they can add them as a friend via request to start chatting.
I have looked around the web to try and answer this question, but cannot find any solid starting point. I am brand new to node.js, express, and socket.io, and would love some help with this issue.
If you could point me in the right direction as to how I can create a friend based system using node, that would be amazing. Thanks!
I too think this is a broad question but I will try to give you the glimpse of a technological aspect of what you are trying to do.
First of all, you should have a user management system, including login, signup, forget password etc. You can use passport.js for this. Now, you have a complete user management system, you can start further.
If you are willing to friend request/accept feature that eventually control the chat system, You might wanna create a database structure like below.
const mongoose = require('mongoose'),
Schema = mongoose.Schema;
// Schema defines how chat messages will be stored in MongoDB
const FriendsSchema = new Schema({
participants: [{ type: Schema.Types.ObjectId, ref: 'user' }],
requestTo: {type: Schema.Types.ObjectId, ref: 'user'},
accepted: {tyoe: Boolen, default:false}
});
module.exports = mongoose.model('Friends', FriendsSchema);
You can check this database to create a friendship request, check friendship between two users etc. And another thing you shoud do in database is to create model for chats. To save messages, Like below:
const mongoose = require('mongoose'),
Schema = mongoose.Schema;
const MessageSchema = new Schema({
friendshipId: {
type: Schema.Types.ObjectId,
required: true,
ref: 'Friends'
},
body: {
type: String,
required: true
},
author: {
type: Schema.Types.ObjectId,
ref: 'user'
},
seen: {
type: Boolean,
default: false
},
delivered: {
type: Boolean,
default: false
}
},
{
timestamps: true // Saves createdAt and updatedAt as dates. createdAt will be our timestamp.
});
module.exports = mongoose.model('Message', MessageSchema);
Now, for the real-time chat system you should integrate both socket.io and databases. You can do it like below code.
var http = require('http')
var redis = require('redis')
var client = redis.createClient()
module.exports = (app) => {
const server = http.createServer(app)
const io = require('socket.io').listen(server)
io.sockets.on('connection', (socket) => {
socket.on('sendChat', (user, msg, messageId) => {
client.get(user, function(err, socketId){
io.to(socketId).emit('updateChat', socket.username, msg, messageId)
})
})
socket.on('delivered', (user, messageId) => {
client.get(user, function(err, socketId){
io.to(socketId).emit('delivered', messageId)
})
})
socket.on('seen', (user, messageId) => {
client.get(user, function(err, socketId){
io.to(socketId).emit('seen', messageId)
})
})
socket.on('adduser', (username) => {
client.set(username, socket.id, function(err){
socket.username = username
io.sockets.emit('updateOnlineUser', username)
})
})
socket.on('disconnect', function(){
client.del(socket.username)
io.sockets.emit('updateOfflineUser', socket.username)
})
})
}
What happens above? It basically create a connection to client and when the client sends a addUser event to server it stores user in radis store. And when messages are transferred through socket, by sending sendChat event, it sends events to another chat user. You will also need to save this chat to database as well.
And when users do not want to send message to inactive users, which are not connected through socket. You must implement endpoints for messaging tasks. For more info please follow through this open source project.

Categories