How to rename a collection without loosing data of collection in Mongoose - node.js

I am using Mongoose in my NodeJs project. I want to rename my collection from OldCollectionName to NewCollectionName.
I tried following:
Mongoose.connection.collection('OldCollectionName').rename('NewCollectionName');
But this is making my collection empty. Can someone suggest how can I change the collection name without loosing my collection data? I need all the data from OldCollectionName in NewCollectionName as well.
I have following schema for my model
const Mongoose = require('mongoose');
const mongooseSequence = require('mongoose-sequence');
const Schema = Mongoose.Schema;
var collectionSchema = new Schema({
collectionIdAutoIncrement: { type: Number,unique: true,index:true,sparse:true},
fieldName: {
type: String,
default: ''
},
otherCollectionId: {
type: Schema.Types.ObjectId,
required: true,
ref: "OtherCollection",
},
created: { type: Date, default: Date.now },
updated: { type: Date},
});
collectionSchema.plugin(mongooseSequence, { inc_field: 'collectionIdAutoIncrement' });
var oldCollection = Mongoose.model('OldCollectionName', collectionSchema);

Related

How to create a dynamic nested mongoose document with the same schema on multiple levels

Before everyone tells me I can't call a const before initializing, I do know that.
But I think this is the simplest way to render the concept I have in mind, (where any subdocument within the replies array also has the same schema as the parent, and documents within the replies array of those subdocuments also having the same schema). I would really appreciate anyone's input.
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
var commentSchema = new mongoose.Schema({
content: String,
createdAt: {
type: Date,
default: Date.now
},
score: {
type: Number,
default: 1
},
username: {
type: String,
lowercase: true
},
parent: {
type: Schema.Types.ObjectId,
ref: 'comment'
},
replyingTo: String,
replies: [commentSchema]
});
module.exports = mongoose.model("comment", commentSchema);
Since a const can't be called before initialization, to fix this issue the parent schema should be called on the children array after initialization the code below:
commentSchema.add({ replies: [commentSchema] })
The final result should look like this:
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const commentSchema = new mongoose.Schema({
content: String,
createdAt: {
type: Date,
default: Date.now
},
score: {
type: Number,
default: 1
},
username: {
type: String,
lowercase: true
},
parent: {
type: Schema.Types.ObjectId,
ref: 'comment'
},
replyingTo: String,
});
commentSchema.add({ replies: [commentSchema] })

How to set "capped" after collection is created?

I am attempting to set a capped parameter to my collection within my mongoose.Schema that did not include capped at first.
Any help welcome.
My Schema:
const mongoose = require('mongoose')
var Schema = mongoose.Schema;
var userSchema = new Schema({
name: { type: String, required: true },
email: { type: String },
password: { type: String },
isAdmin: {type: Boolean, default: false},
avatar: { type: String },
joinDate: { type: Date, default: Date.now() },
},{ autoCreate: true, capped : 1024})
userSchema.set('timestamps', true);
const Users = mongoose.model('Users', userSchema)
module.exports = Users;
I get following error:
Error: A non-capped collection exists with the name: users
To use this collection as a capped collection, please first convert it.
Seems like you have already created a users collection in your database. So to convert it into a capped run below command either in mongoshell or robomongo
db.runCommand( { convertToCapped: 'users', size: 1024 } )

Mongo Relationships/Referencing

I am new to MongoDB references. Right now I have one collection which I call users. It stores all users and their keys. I have another collection which has data for each key.
I want to just use their key as the ID to connect them. So I will have each key generated and and the keyData will be empty when first created and then I will just keep adding objects to the keyData array. That is my plan, but I do not know how I create the relation with the schema.
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
//Create Schema
const userKey = new Schema({
_id : {
type : String,
required: true
},
key: {
type : String,
required: true
},
keyData: [key],
date: {
type: Date,
default: Date.now
}
});
module.exports = Key = mongoose.model('key', userKey);
This doesn't work because I cannot access the key before initialization. So how canI relate the two collections?
Schema #1: userData
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
// Create User-data Schema
const userData = new Schema({
data: {
type: Array,
require: true
}
},
{
collection: 'data' // Mentioning collection name explicitly is good!
});
module.exports = mongoose.model('data', userData);
Schema #2: Keys
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
// Create User-Key Schema
const userKey = new Schema({
key: {
type: String,
required: true
},
keyData: {
type: Schema.Types.ObjectId,
ref: 'data'
},
date: {
type: Date,
default: Date.now
}
},
{
collection: 'keys' // Mentioning collection name explicitly is good!
});
module.exports = mongoose.model('keys', userKey);
As per this link its not possible to set string as refs. So in your keys schema use ObjectId as ref.
Would something like this work?
const userData = new Schema({
_id : {
type : String,
required: true
},
data : {
type : Array,
require: true
}
});
const userKey = new Schema({
_id : {
type : String,
required: true
},
key: {
type : String,
required: true
},
keyData: [{ type: Schema.Types.ObjectId, ref: 'data' }],
date: {
type: Date,
default: Date.now
}
});
module.exports = KeyData = mongoose.model('data', userData);
module.exports = Key = mongoose.model('key', userKey);

node mongoose update two collections

I have two schemas, a "projects" schema, and an "applications" schema.
What is the most efficient way of creating a new entry in a collection and updating an existing entry in another collection based on data inside the new entry? Can I avoid making multiple API requests and somehow run a "stored procedure" on the mongoDB end to handle updating the Projects collection when there is a change in the Applications collection?
In this scenario, ideally when an application for a project is created, a new entry is created in the Applications collection and the Project in the Projects collection is updated to reflect the information in the Application.
Can I do this without making multiple api requests?
Project Schema:
// models product.js
const mongoose = require('mongoose');
const { ObjectId } = mongoose.Schema;
const projectSchema = new mongoose.Schema({
name: {
type: String,
trim: true,
required: true,
maxlength: 32
},
applications: {
type: Number,
default: 0
},
created_by: {
type: ObjectId,
ref: 'User'
},
applicants: {
type: Array,
default: []
}
}, {timestamps: true}
);
module.exports = mongoose.model("Project", projectSchema);
Application Schema:
const mongoose = require('mongoose');
const applicationSchema = new mongoose.Schema({
applicantId: {
type: ObjectId,
ref: 'User'
},
ownerId: {
type: ObjectId,
ref: 'User'
},
projectId: {
type: ObjectId,
ref: 'Project'
}
}, {timestamps: true});
module.exports = mongoose.model("Application", applicationSchema);
Note that these are separate schemas because they each carry around 15 fields, i've trimmed them down to post this question.
I suggest to use hooks for mongoose model, there is a post save hook which you can use on Application model to update Project and increment application count.
EDIT - Added Pseudo Code
Project Model
// models -> project.js
const mongoose = require('mongoose');
const {
ObjectId
} = mongoose.Schema;
const projectSchema = new mongoose.Schema({
name: {
type: String,
trim: true,
required: true,
maxlength: 32
},
applications: {
type: Number,
default: 0
},
created_by: {
type: ObjectId,
ref: 'User'
},
applicants: {
type: Array,
default: []
}
}, {
timestamps: true
});
projectSchema.statics = {
/**
* Find project by _id
*
* #param {ObjectId} _id
* #api private
*/
get: function (_id) {
return this.findOne({
_id
})
.exec();
}
}
module.exports = mongoose.model("Project", projectSchema);
Application Model
const mongoose = require('mongoose');
const projectModel = require("./project")
const applicationSchema = new mongoose.Schema({
applicantId: {
type: ObjectId,
ref: 'User'
},
ownerId: {
type: ObjectId,
ref: 'User'
},
projectId: {
type: ObjectId,
ref: 'Project'
}
}, {
timestamps: true
});
// Async hook
applicationSchema.post('save', function (doc, next) {
const relatedProject = projectModel.get(doc.projectId);
relatedProject.applications++;
relatedProject.save();
next();
});
module.exports = mongoose.model("Application", applicationSchema);

MongooseJS: Subdoc Schemas in Separate Files

Let's say that I have a schema called LeagueSchema, which needs to contain some general information about the league (e.g. the name, time created, etc.), as well as some more complicated objects (e.g. memberships). Because these memberships are not needed outside of the league, I don't think it's necessary for them to be their own collections. However, I think for the sake of modularity it would be best for these schemas to live in their own separate files.
It would look something like this:
league.js
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var LeagueSchema = new Schema({
created: {
type: Date,
default: Date.now
},
updated: {
type: Date,
default: Date.now
},
name: {
type: String,
default: '',
trim: true
},
memberships: [MembershipSchema]
});
membership.js
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var MembershipSchema = new Schema({
startDate: {
type: Date,
default: Date.now
},
endDate: {
type: Date,
default: null
},
user: {
type: Schema.ObjectId,
ref: 'User'
}
});
Unfortunately, this doesn't work. I get the following error:
ReferenceError: MembershipSchema is not defined
This is obviously happening because LeagueSchema is dependent on MembershipSchema, but I'm not sure what the best way to include it is. Can I define it as a dependency somehow? Or should I just include the file?
Also, is it bad practice to use subdocuments this way? Is there any reason it would be better to let all of these objects live in their own collections?
In your membership.js, export the membership sub-doc schema as a module:
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var MembershipSchema = new Schema({
startDate: {
type: Date,
default: Date.now
},
endDate: {
type: Date,
default: null
},
user: {
type: Schema.ObjectId,
ref: 'User'
}
});
module.exports = MembershipSchema;
You can then require the exported module schema in your LeagueSchema document:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var MembershipSchema = require('./membership');
var LeagueSchema = new Schema({
created: {
type: Date,
default: Date.now
},
updated: {
type: Date,
default: Date.now
},
name: {
type: String,
default: '',
trim: true
},
memberships: [MembershipSchema]
});
To answer your second question, as a general rule, if you have schemas that are re-used in various parts of your model, then it might be useful to define individual schemas for the child docs in separate files as so you don't have to duplicate yourself. A good example is when you use subdocuments in more that one model, or have two fields in a model that need to be distinguished, but still have the same subdocument structure.
If your memberships are not used elsewhere then rather treat the schema as an embedded document (document with schema of its own that is part of another document, such as items within an array):
Example definition and initialization:
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var MembershipSchema = new Schema({
startDate: {
type: Date,
default: Date.now
},
endDate: {
type: Date,
default: null
},
user: {
type: Schema.ObjectId,
ref: 'User'
}
});
var LeagueSchema = new Schema({
created: {
type: Date,
default: Date.now
},
updated: {
type: Date,
default: Date.now
},
name: {
type: String,
default: '',
trim: true
},
memberships: [MembershipSchema]
});
mongoose.model('League', LeagueSchema);
Your membership.js file should export the schema and the league.js file should import it. Then your code should should work.
In membership.js towards the bottom add:
module.exports = MembershipSchema;
In league.js, add
var MembershipSchema = require('membership.js');

Resources