create dynamically mongo collection in mongoose - node.js

create dynamically mongo collection in mongoose. I tried below code: suggest me please
function residenceModel(regionName){
const residenceSchema = new Schema({
key:String,
value:String
}, { strict: false });
return mongoose.model(
`residence_meta_${regionName}`,
residenceSchema,
`residence_meta_${regionName}`
);
}
console.log(residenceModel);
exports.ResidenceModel = residenceModel;

You can create dynamic model with this simple steps
create a file dynamicModel.js
const mongoose = require('mongoose')
//import mongoose from 'mongoose'
const Schema = mongoose.Schema
const dynamicModel = (regionName) => {
const residenceSchema = new Schema({
key:String,
value:String
}, { strict: false })
return mongoose.model(
`residence_meta_${regionName}`,
residenceSchema,
`residence_meta_${regionName}`
);
}
module.exports = { dynamicModel }
// export default { dynamicModel }
On file where you want to include or create model let's say app.js
// Please take care of path
const { dynamicModel } = require("./dynamicModel")
//import { dynamicModel } from "./dynamicModel";
.....
.....
// User this method to create model and use It
const countryModel = dynamicModel("country")
countryModel.create({ key:"country", value:"USA" });
Use this method multiple time, Give it a shot and let me know

I fixed this issue. below is the code. you guys can use it.
function createMetaCollection(regionName){
console.log(regionName);
var residenceSchema = new Schema({
region:String,
customer_type:String,
},{strict: false});
residenceSchema.plugin(autoIncrement.plugin,{model:'resident_meta_'+regionName,field:regionName+'id',startAt:1});
exports.Typeof_employment_meta = mongoose.model('resident_meta_'+regionName,residenceSchema,'resident_meta_'+regionName);
}

Related

Mongoose query doesn't work with the filter

I'm testing a nodejs snippet to do iteration with my example mongodb collection users. But the query never worked. The full users collection are printed.
The standalone mongodb is setup in EKS cluster.
Why the query {name: "Baker one"} didn't work?
The code is:
const mongoose = require("mongoose");
const url = "mongodb://xxxxxx:27017/demo";
main().catch(error => console.error(error.stack));
async function main() {
// Connect to DB
const db = await mongoose.connect(url);
console.log("Database connected!");
const { Schema } = mongoose;
// Init Model
const Users = mongoose.model("Users", {}, "users");
const users = await Users.find({name: "Baker one"}).exec();
// Iterate
for await (const doc of users) {
console.log(doc);
console.log("users...");
}
console.log("about to close...");
db.disconnect();
}
The users collection:
The execution result:
$ node modify.js
Database connected!
{ _id: new ObjectId("610f512c52fa99dcd04aa743"), name: 'Baker one' }
users...
{ _id: new ObjectId("61193ed9b8af50d530576af6"), name: 'Bill S' }
users...
about to close...
This line could be the culprit (note that the schema has been defined with no fields like Joe pointed out in the comments).
const Users = mongoose.model("Users", {}, "users");
In this case, I had to add StrictQuery option in the Schema constructor to make it work, like so:
const userSchema = new Schema({}, { collection: "Users", strictQuery : false });

Typeerror : 'todo.find is not a function'

I'm adding a new Model to my app but it's failing with "TypeError: todo.find is not a function". I have another model, Items, that are set up in the same way and are working fine. Things seem to be failing in the route but it works if I hook it up to the Item model. don't know what's going on wrong?
model
var mongoose = require('mongoose');
var todoSchema = new mongoose.Schema({
name: {
type: String,
required: true,
maxlength:32,
trim:true
}
},{timestamps:true}
)
module.exports = mongoose.model('Todo',todoSchema)
auth.js//route
var express = require('express');
var router = express.Router();
const {getAllTodos} = require('../controller/auth');
router.post('/getalltodo',getAllTodos);
module.exports = router;
auth.js//controller
const Todo = require('../model/todo');
exports.getAllTodos = (req,res) =>{
const todo = new Todo(req.body)
todo.find().exec((err,todo) =>{
if(err || !todo){
return res.status(400).json({
error : 'No Todos found'
})
}
res.json(todo);
})
}
You have a problem in your getAllTodos middleware. You try to do this:
const todo = new Todo(req.body); // returns a Document
todo.find()... // a Document doesn't have a 'find' method
You don't have a find method on a Document but you do have one on a Model.
Do this instead:
Todo.find()...
Look at the docs if you need more info.

Mongoose Populate cant get this to work?

book.schema.js
const mongoose = require('mongoose')
const Schema = mongoose.Schema
const BookSchema = new Schema({
name: {
type: String,
required: true
}
})
module.exports = BookSchema
book.model.js
const mongoose = require('mongoose')
const BookSchema = require('../schema/book.schema')
const Book = mongoose.model('Book', BookSchema)
module.exports = Book
novel.schema.js
const mongoose = require('mongoose')
const Schema = mongoose.Schema
const NovelSchema = new Schema({
name: {
type: String,
required: true
},
type: {
type: Schema.Types.ObjectId,
ref: 'Book'
}
})
module.exports = NovelSchema
novel.model.js
const mongoose = require('mongoose')
const NovelSchema = require('../schema/novel.schema')
const Novel = mongoose.model('Novel', NovelSchema)
module.exports = Novel
query
// Mongoose Populate cant get this to work
// I am at a loss
Novel.findById('5b87310d41073743856a7c4a').populate({
path: 'books'
})
mongoose populate not working。
Please let me know what I am doing wrong or give me a simple explanation...Thank you...
You are right to use the populate for loading the subdocument, but you need to pass the name of the book field in the novel schema, in your case the name is type.
Here is the link to documentation with some examples: Mongoose Populate
And below is the more one solution to your problem:
let book = await new BookModel({name:"book test"}).save();
console.log('-----------BOOK ITEM-------------');
console.log(book);
let novel = await new NovelModel({name:"novel test",type:book._id}).save();
console.log('-----------NOVEL ITEM-------------');
console.log(novel);
let itemPopulated = await NovelModel.findById(novel._id)
.populate('type')
.then((result) => {
return result;
}).catch((err) => {
console.log(err);
});
console.log('-----------ITEM POPULATED-------------');
console.log(itemPopulated);
And the execution output:
The parameter on the function populate() is the path of the field you want to populate, and also when you use populate or any chained function in mongoose you have to use the exec() function in the ending, so the correct way to do it would be:
Novel.findById('5b87310d41073743856a7c4a').populate({
path: 'type'
}).exec()

How to implement more than one collection in get() function?

My model university.js
const mongoose = require('mongoose');
const UniversitySchema = mongoose.Schema({
worldranking:String,
countryranking:String,
universityname:String,
bachelorprogram:String,
masterprogram:String,
phdprogram:String,
country:String
},{collection:'us'});
const University =module.exports = mongoose.model('University',UniversitySchema);
My route.js
const express = require('express');
const router = express.Router();
const University = require('../models/university');
//retrieving data
//router.get('/universities',(req,res,next)=>{
// University.find(function(err,universities){
// if(err)
// {
// res.json(err);
//}
// res.json(universities);
//});
//});
router.get('/usa',function(req,res,next){
University.find()
.then(function(doc){
res.json({universities:doc});
});
});
module.exports= router;
How to implement multiple collections in this get() function? I put my collection name in the model. Please help me with a solution to call multiple collections in get() function.
Here is Example to use multiple collection names for one schema:
const coordinateSchema = new Schema({
lat: String,
longt: String,
name: String
}, {collection: 'WeatherCollection'});
const windSchema = new Schema({
windGust: String,
windDirection: String,
windSpeed: String
}, {collection: 'WeatherCollection'});
//Then define discriminator field for schemas:
const baseOptions = {
discriminatorKey: '__type',
collection: 'WeatherCollection'
};
//Define base model, then define other model objects based on this model:
const Base = mongoose.model('Base', new Schema({}, baseOptions));
const CoordinateModel = Base.discriminator('CoordinateModel', coordinateSchema);
const WindModel = Base.discriminator('WindModel', windSchema);
//Query normally and you get result of specific schema you are querying:
mongoose.model('CoordinateModel').find({}).then((a)=>console.log(a));
In Short,
In mongoose you can do something like this:
var users = mongoose.model('User', loginUserSchema, 'users');
var registerUser = mongoose.model('Registered', registerUserSchema, 'users');
This two schemas will save on the 'users' collection.
For more information you can refer to the documentation: http://mongoosejs.com/docs/api.html#index_Mongoose-model or you can see the following gist it might help.
Hope this may help you. You need to modify according to your requirements.

Mongoose - Can't push a subdocument into an array in parent Document

I am trying to push a subdocument(ApplicationSchema) into my Job schema. But it doesn't seem to work.
Following is my Job Schema :
import mongoose from 'mongoose';
const Schema = mongoose.Schema;
var ApplicationSchema = require('./Application');
const Job = new Schema({
skills : {
type : Array
},
active : {
type : Boolean,
default : false
},
applications: [ApplicationSchema],
userId : {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
}
},{timestamps : true});
export default mongoose.model("Job", Job)
This is subdocument(ApplicationSchema). I have 5 more subdocuments in this schema.
I am pushing an object with a key-value pair of talentId and its value. But it doesn't work.
I get a new object in the array but the object I'm trying to push is not pushed.
import mongoose from 'mongoose';
const Schema = mongoose.Schema;
var notesSchema = require('./notesSchema');
var documentSchema = require('./documentSchema');
var assessmentSchema = require('./assessmentSchema');
var interviewScheduleSchema = require('./interviewScheduleSchema');
var referenceSchema = require('./referenceSchema')
const ApplicationSchema = new Schema({
talentId: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Talent'
},
applicationType: {
type: Number
}
notes: [notesSchema],
documents: [documentSchema],
assessment: [assessmentSchema],
interviewSchedule: [interviewScheduleSchema],
references: [referenceSchema]
},{
timestamps: true
});
export default ApplicationSchema;
Following is my code in the API endpoint
.post((req, res, next) => {
Job.findById(req.params.jobId)
.then((job) => {
if (job != null) {
job.applications.push(req.body);
job.save()
.then((job) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.json(job);
})
}
else {
err = new Error('Job ' + req.params.jobId + 'not found')
err.status = 404;
return next(err);
}
}, (err) => next(err))
.catch((err) => next(err));
})
req.body contains following object
{ talentId: '5a813e1eb936ab308c4cae51' }
If you already have the id of the job document then you can push application object direct by doing the following:
Job.update(
{ _id: req.params.jobId },
{ $push: { applications: req.body} },
callback
);
or you can use promise to handle this. and if you are only saving id of the application then you may want to change your job schema to store Id of the applications instead of whole application schema.
Please read the documentation carefully as this is very basic update query.
You have,
talentId: {type: mongoose.Schema.Types.ObjectId,
ref: 'Talent'}
But your req.body contains:
{ talentId: '5a813e1eb936ab308c4cae51' }
It should be:
{ talentId: mongoose.Types.ObjectId('5a813e1eb936ab308c4cae51') }
Turns out there was nothing wrong with code.
I was using import and export default syntax which didn't seem work well with this.
import mongoose from 'mongoose';
const Schema = mongoose.Schema;
and
export default ApplicationSchema;
I replaced them with Common JS syntax and everything worked fine.
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
and
module.exports = ApplicationSchema;
I did this for Job document file and every subdocument file and the code worked.

Resources