What happens if I delete a Model class (.js) in Node JS - node.js

I recently started taking a course on Node JS and Mongo DB. During the course, I created a model class:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const IdeaSchema = new Schema({
title: {
type: String,
required: true
},
details: {
type: String,
required: true
},
date: {
type: Date,
default: Date.now
}
});
mongoose.model('ideas', IdeaSchema);
This created a 'table' (correct me if I'm wrong) in the MongoDB database, and editing the class changed the design of the table. So, what happens if I delete the class? Does the 'table' get deleted? Why? And if not, how can I delete it?

Everything in Mongoose starts with a Schema. Each schema maps to a MongoDB collection and defines the shape of the documents within that collection. It's just a blueprint of the house, deleting the Schema doesn't mean you are deleting the actual physical house or in mongoDB the collection.
You can change your schema anytime, without having any changes / effect on your old documents. You can still retrieve it and add new documents with new added fields based on the new modified schema.
To easily manage your mongoDb data, you can install tools like Robo3T see https://robomongo.org If you are new in mongo, this kind of tools will save you time and help you manage your dbs and collections easily. Everytime you change / add new schemas, you can use the tool to delete db, delete collections, insert documents, etc.
Or if you are just accessing mongo via terminal, this mongo shell commands will help you https://www.opentechguides.com/how-to/article/mongodb/118/mongodb-cheatsheat.html
For more details on mongoose schema, see https://mongoosejs.com/docs/guide.html

your table didn't get deleted. just your schema changed and added your new field in same table.

Related

Should I create New Schema Model file for every route OR use already created Schema?

Suppose I have a User Schema which has around 30 fields, and other 3 schemas also.
UserSchema.js
user_schema = new Schema({
user_id: { type: String},
.........//30 properties
});
ctrs_schema = new Schema({
.........10 properties
});
ids_schema = new Schema({
.........5 properties
});
comments_schema = new Schema({
.........10 properties
});
Now I am writing a route which will change the gender of the user, Now in order to do it I can use UserSchema.js but that will load all of the schemas into my route, whereas if I would have created a new file which had only one schema with two fields, then all schemas will not get loaded into the memory for the route.
UserGenderSchema.js
gender_schema = new Schema({
user_id: { type: String},
gender: { type: String}
});
I know there are pros and cons of both of the ways
Pros -
I have to edit only in single file if I would have to change something
for any field.
Cons -
All Schemas are Loading for all routes which are unnecesary. Memory
Wastage.
Will, there be any less memory usage between both of the ways on the threads?
Can anyone Please tell me which architecture will be better or what you are implementing in your project and why?
Thanks
It's better to keep user related fields in just one schema, cause mongo has been there because of its non-relational structure and it gained its performance by keeping relational structures away, so if you create a schema for each field and then create a reference in each of them to point out to the user they are related to, you are kind of using mongo to build a heavily relational structure and mongo is not good as it should be in this situation, so if later on your application you want to somehow show all the information of the user or try to update multiple fields of user or try to show more information of the user in one of your routes or something, you will end up having some serious performance issues. as a conclusion, the cost of loading all the schema to touch only one field is not as much as the cost of breaking down your data structure.

Missing data in MongoDB (Mongoose/MLab) after successful search using the same field

I have a very specific question. I have a web project that is using Express (Node.JS) and MLab (MongoDB/Mongoose). I've manually edited several records in a collection (yeah, I know, bad idea) and am using one of those fields in a Mongoose search. The schema is defined as follows: (relevant part only)
user: {
id: {
type: mongoose.Schema.Types.ObjectId,
ref: "Registration"
},
username: String,
type: String
}
My search is as follows:
Master.find({$or: [{'user.type': 'committee'}, {'user.type': 'admin'}]}, function(err, foundUsers) {
do stuff
});
The search works just fine (using 'user.type'), but the user object in each record is undefined in foundUsers.
What am I missing?
Thanks!
Found it. I tried to pull a fast one and add something to the user record that wasn't in the Registration Schema. Mongo was smarter than I was in this case.

How to handle creation of referenced documents in Mongoose and Node?

I have a Node.js API method that creates a Track document and then creates Task document (which has DBRef to a Track to work on) to actually convert and upload it to s3 (specific operations doesn't really matter). I use Mongoose to perform operations on my MongoDB.
So my question is there any way to avoid having "stalled" tracks that have Track document created and no Task for them? Creating a Task without Track is fine though, but in that case we don't have DBRef until we create a Track document and then update a Task document which may fail due to server restart or something.
In traditional RDBMS that kind of problem is easy to solve since I would do that in a single transaction.
Thanks in advance.
Update:
My schemas look like that:
var Track = new Schema({
name: String,
...
});
var Task = new Schema({
track: {type: Schema.Types.ObjectId, ref: 'Track'},
created: {type: Date, default: Date.now}
});

How do I get Mongoose to find none Mongoose created data within MongoDB?

Can someone please stop me from going insane!
I have a MongoDB database which has a simply database that was created and populated via Mongoose, this works great I can perform finds woth no problems at all.
I went into the Mongo console and created a new database with just use newDB and the performed a simple insert, I inserted several records and they appeared fine within Mongo. I can find on them and so all the Mongo operations but when I try to perform a find on this database Mongoose returns a null???
I have noticed that the database I created in Mongo console does not create the '__v' field which I believe is for Mongoose internal indexing uses, I have created this field in my custom tables but still no joy I just cannot create data from outside of Mongoose and use it within my app??????
I have spent hours looking into this and reading maybe I just missed something but honestly I cannot find a thing on this and many people must hit this every week????
**Sorry here is the code I am running against the database:
exports.adduser = function(req, res){
var mongoose = require("mongoose");
mongoose.connect("localhost/nm", function(err){
if(err)throw(err);
console.log("Connected to MongoDB successfully...")
var schema = mongoose.Schema({
Firstname: String,
Lastname: String,
MiddleInitial: String,
Password: String,
Username: String
});
var auser = mongoose.model("Users", schema);
auser.find({}, function(err, alist){
console.log(">>>>"+alist);
});
});
**
Thanks again!!!!! for your input it is very much appreciated....
try inspecting mongo instance with
show dbs
use <dbName>
in mongo shell to make sure you are using the right database and then
show collections
or alternatively
db.getCollectionNames()
To see if your collections are there or not.
__v is a document version property incremented only for array operations(mongoose 3).
Your connection string might be wrong.
Anyone experiencing this problem and I know there are a good few read the comment by robertklep above it solved my problems very quickly!
DOnt know how the accept a comment sorry!

(re)Populating mongodb collection from json - mongoose

Hi is there a way to repopulate a mongo collection from a json array using mongoose?
I have this schema.
var UserNote_Schema = new Schema({
user_id: {type:ObjectId, ref:require('../User/User_Schema.js')},
note: {type:String},
created: {type:Date},
last_mod: {type:Date}
});
and would like to populate it with this json and have it save to the collection.
{"_id":"506b8922a6bd97d322000011",
"user_id":"504aaeef898f541527000012",
"note":"a note","created":"2012-03-10T00:38:58.000Z",
"last_mod":"2012-03-10T00:38:58.000Z"}
My goal is to reset my database to a certain state after running some tests which add remove and change some of the data within.
However, if there is more convenient way of achieving a database reset from a previous state in mongoose/mongo I'd much appreciate any pointers. Keeping the versioning info would also be nice.
thanks

Resources