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
Related
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")
}
I have a table and a form that retrieves datas and sends them to a database. After submitting the form, a new table rows is created with the datas just submitted.
I'd like to add a field for each rows with the date and time of the submit.
If I click on submit button, I do a http post request.
Is it possible to save the time and date of the submit?
I'm using mongoose for the db and express for the router.
import Router from 'express';
const router = Router();
router.post('/', isAuthorized(), async (req, res) => {
try {
let fruit = new Fruits(req.body);
await fruit.save();
res.json(fruit);
} catch (err) { res.status(503).send(err); }
});
You can set the timestamps of the POST request on the server-side, with your mongoose models.
In your mongoose Fruits Schema, you can add a timestamps field, with the default set to new Date(). So something like this:
const mongoose = require("mongoose");
const FruitSchema = new mongoose.Schema({
... other Fruit properties...
timestamps: { type: Date, default: () => new Date() }
});
Or instead, you can utilize mongoose's built in timestamps, by passing in a second object to your Schema, like this:
const mongoose = require("mongoose");
const FruitSchema = new mongoose.Schema({
... Fruit properties ...
}, {
timestamps: true
});
This will automatically add createdAt and updatedAt to your newly created Fruits documents.
You can get date and time using the Date object.
pass the below code into the code wherever you want to save. (like MongoDB)
let date_ob = new Date();
Read more about Date
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.
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.
EDIT
I think I've found the problem...
I tried using process.env.PWD somewhere and it all works, except for Mongoose. Deleted it's usage and everything suddenly works. Can someone explain why?
END EDIT
On startup, my app does a few things like defining routes and setting up Mongoose.
/init/db.js
module.exports = function () {
const {url, options} = getCredentials();
mongoose.connect(url, options);
// This requires the files that have the schemas in 'm
loadSchemas();
console.log(require('mongoose')); // Shows all models
};
Example Schema File (user.js)
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const User = new Schema({
username: {type: String, required: true, unique: true},
email: {type: String, required: true, unique: true},
registration_date: {type: Date, default: Date.now, required: true},
birthdate: {type: Date}
});
mongoose.model('User', User);
In /init/db.js, a log on require('mongoose'); still shows all the models and are accessible, right after that function call, a log on require('mongoose') shows a mongoose object like it was just now created.
app.js
require(`${process.env.APP_DIR}/init/db`)();
console.log(require('mongoose')); // Not a single model in it
When normally starting the app, there are no problems here, but because I've also written DB unit tests, it's crashing on them with the error
throw new mongoose.Error.MissingSchemaError(name);
^
MissingSchemaError: Schema hasn't been registered for model "User".
Use mongoose.model(name, schema)