How to delete the data across the collections - node.js

Let's say, I have collections like
let employee = mongoose.Schema({
name: String,
email: String,
department: String,
doj: Date,
address: String
});
let student= mongoose.Schema({
name: String,
email: String,
department: String,
doj: Date,
address: String
});
let manager= mongoose.Schema({
name: String,
email: String,
department: String,
doj: Date,
address: String
});
in my database. I need to delete every data which has department "Computer Science" in each collection(employee, student, manager). I don't know how to do it. I tried deleting data by getting collection names from my database first then querying to remove each data as I said, but it doesn't work as I expected, always return error"db.getCollectionName is not a function". Any idea how to remove data across the multiple collections at the same time?. I am using node js,express and MongoDB.

To delete matching records for all collections, you can loop through all the models you have registered with Mongoose.
Object.keys(connection.models).forEach(async(collection) => {
const usersss = mongoose.model(collection)
await usersss.deleteMany({ defaultAccountId: userParam.defaultAccountId, grnNo: userParam.grnNo })
})

Related

How to define an object in NodeJS schema?

I currently have a schema like this:
const postSchema = mongoose.Schema({
title: String,
message: String,
name: String,
creator: String,
tags: [String],
selectedFile: String,
likes: { type: [String], default: [] },
createdAt: {
type: Date,
default: new Date(),
},
})
One of the problem that I anticipate is that as the number of users grow, searching the likes array will become inefficient. Is there a way to store the likes array instead as an Object (key would be userId and value could be true) so that finding someone in the Object would become more efficient.
I am also open to hearing any other ideas that you might have.
Thanks!
I want to suggest populate() for this. From that, you can manage a large no. of user information without a problem. You can create a new schema as likes and add the id of the likes document as an id with the populate. Check the below example.
const likeSchema = mongoose.Schema({
type: [String],
default: [] },
});
const Like = mongoose.model("Like", likeSchema);
Then create the postschema like below.
const postSchema = mongoose.Schema({
title: String,
message: String,
name: String,
creator: String,
tags: [String],
selectedFile: String,
likes: {
type: mongoose.Schema.Types.String,
ref: 'Like',
},
createdAt: {
type: Date,
default: new Date(),
},
})
const Post = mongoose.model("Post", postSchema);
You can easily get all the data inside a likes document by populating when running a query like below.
const posts = await Post.findById({creator_id}).populate("likes");
//Below code will print the data of the first element of the type array of relevant likes document.
console.log(posts.likes.type[0]);
Check the populate and population sections of the mongoose documentation to learn more.

Creating different types of users in mongodb

I want to create an API to register, login and other things. two types of users
A teacher and a student , I'm using MongoDb and defining the schema.
const UserSchema = new Schema({
studentInfo : {
name: String,
email: String,
password: String,
birthday: Date,
state: String,
zip_code: String,
address: String,
phone_number: String,
},
teacherInfo : {
name: String,
email: String,
password: String,
birthday: Date,
state: String,
zip_code: String,
address: String,
phone_number: String,
course: {
title: String,
price: Number,
description: String
}
},
role: String
});
is this a good approach? or there is a better way?
I added the role field to perform route guarding on the front end.
I'm using Nodejs and Express.
any help will be much appreciated, thank you.
This is one way of embedding both student and teacher object in the same document and you can simply get data with single query. Although you don't need to separately embed the common fields in object like name, email, password, phone_number etc. teacherInfo would be like this
teacherInfo : {
course: {
title: String,
price: Number,
description: String
}
}
You can create different schemas for student and teacher (as they are unique and you might need them independent sometimes), and make User as the base model.
var User= new Schema({
name: String,
email: String,
password:String,
birthday: Date,
state: String,
zip_code: String,
address: String,
phone_number: String,
_teacher:{type:Schema.Types.ObjectId, ref:'Teacher'},
_student: {type:Schema.Types.ObjectId, ref:'Student'}
});
If _teacher has a value then the user can be considered as a teacher.
If _student has a value then the user can be considered as a student.
//Teacher Model
var Teacher = new Schema({
course: {
title: String,
price: Number,
description: String
},
//other teacher's fields
})
//Student Schema
var Student= new Schema({
//student's fields if you need in future
})

mongoDB schema changes results in error for old users?

I have a schema in my server like this:
deliveryAddress : {
city: String,
state: String,
country: String,
zipcode: String
}
but because of future enhancement we were required to add phone number to this deliveryAddress collection object. but the user who are already registered will face the problem how do i solve this.
The schema should look like this in future:
deliveryAddress : {
city: String,
state: String,
country: String,
zipcode: String,
phoneNumber:String
}

MongoDB trouble, is both way references a thing?

So I have a website built with node.js + mongoDB (mongoose). I'm having a bit trouble in the design of the database.
I want to have 2 logins, one for institutions and another for professionals. Do I need to double reference them (like the professional has a ref to Inst and an institution has a ref to the professional)?
For instance, If I want to display the list of all professionals when I login with an institution is trivial but if I don't ref the institution on the User (professional) is not so simple. So which one is better? Having code to find the user in every institution and get its institution name or both referencing each other and then do a populate?
If I pick both referencing each other, is there some way to guarantee that both of them will always be linked and having no broken only one way references?
Code:
var userSchema = new mongoose.Schema({
username: String,
password: String,
email: String,
name: String,
created_at: {type: Date, default: Date.now},
status : Boolean,
institution: { type:mongoose.Schema.ObjectId, ref:'Inst' }
});
mongoose.model('User', userSchema);
var User = mongoose.model('User');
var instSchema = new mongoose.Schema(
{
name : String,
professional : [{ type:mongoose.Schema.ObjectId, ref:'User'}]
});
mongoose.model('Inst', instSchema);
var Inst = mongoose.model('Inst');
How about just merge instSchema into userSchema as below, with additional user_type to indicate which type this user belong to, Professional or Institutions. Also one new related_user to store the other related User documents
var userSchema = new mongoose.Schema({
username: String,
password: String,
email: String,
name: String,
created_at: {type: Date, default: Date.now},
status : Boolean,
user_type: {type: String, enum: ['Prof', 'Inst']},
related_user: [{ type:mongoose.Schema.ObjectId, ref:'User'}]
});
mongoose.model('User', userSchema);
var User = mongoose.model('User');

Mongoose - Redefining schema structure

I have the following code:
var Schema = mongoose.Schema;
var personSchema = new Schema({
firstname: String,
lastname: String,
address: String,
});
var Person = mongoose.model('humans', personSchema);
var john = Person({ //will turn into a new object.
firstname: "john",
lastname: "doe",
address: "somewhere",
});
//save the user
john.save(function(err){
if(err) throw err;
console.log('person saved!');
});
now, in my database, I have a collection called humans with
firstname: "john",
lastname: "doe",
address: "somewhere",
as you can see above. My question is: is there a way that inside the humans collection, there will be 1 document that will have the structure you see above, and one with some new fields:
firstname: String,
lastname: String,
address: String,
car: String,
office: String
I have tried a couple of ways to redefine the structure of the personSchema
but it's always giving me the same error, Cannot overwrite model once compiled.”
Thank you for your time.
The error is occurring because you already have a schema defined, and then you are defining the schema again. Instantiate the schema once and the make Global object to access schema.
Change your Person schema, and add new fields
var personSchema = new Schema({
firstname: String,
lastname: String,
address: String,
car: String,
office: String
});
Documents which does not contain added fields after populating will have this keys but with undefined values.
For not ignoring new properties you can unstrict schema
var personSchema = new Schema({
firstname: String,
lastname: String,
address: String,
car: String,
office: String
}, {strict: false});
Also you can use Mixed type to set anything to property
var personSchema = new Schema({
firstname: String,
lastname: String,
additional: Mixed
});
And set other properties in additional field.

Resources