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