Traverse the mongo DB scheme in Mongoose JS - mongodb

I'm trying to find out if Mongoose.JS exposes subDocuments with in the .modelSchema. The basic idea is that I want to generate a tree view of my database model.
For Exampe I a status schema that allow each status to have an array of questions that are made from a Question Schema. My Mongoose Schema looks like this:
var StatusScheme = new Schema ({
StatusName: {type: String },
isClosed: {type:Boolean},
Questions:[QuestionSchema]
});
var QuestionSchema = new Schema ({
QuestionName: {type: String },
isRequired: {type:Boolean},
QuestionType:{type: String }
});
Now in my node.js app I want to iterate the schema to generate a tree of field names:
+StatusName
+isClosed
+Questions
+QuestionName
+isRequired
+QuestionType
I was exploring in the .modelSchemas[schema].tree object and I can get all of my field names the problem is I can't detect if the Questions array is really a different schema. Does anyone have any insight into the object that may tell me this? Once I know that a field is really a subdocument I can recursivly iterate the entire schema to build my tree.
I think I may have found the link. I can take a look modelSchemas object and dig into each path looking to see if the path has a caster object. If it does I can then fill it with the sub document data.
isClosed is not a subDocument and Questions is a subdocument. It looks like Mongoose then includes the constructor for in in the modelschema. Any thoughts on a better way to find the "tree" view or sub document relation within Mongoose.

Details can be found # https://groups.google.com/forum/#!topic/mongoose-orm/4sBbi388msI
A Child schema must be defined before it is embedded as a sub document.
To find the sub document schema traverse to "CaseSchema.paths["MYRecipients"].options.type[0]"
The tree property also contains the nested relationship between schemas.

Related

Mongoose: Populate on existing DBRef

I am migrating a Spring project to Nextjs&co for personal enrichment.
I have an existing mongodb database with school related collections such as:
// school (as json)
"_id" : ObjectId("5f457f041291df2910dea1ed"),
"name" : "San Lucas Primary School",
...
"campus" : DBRef("campus", ObjectId("5f457dd9126d210893e14e11"))
I've loaded up mongoose, and have tried to wrangle it for the last few days to get it to populate campus.
If I define the schema like so:
import mongoose from 'mongoose'
const SchoolSchema = new mongoose.Schema({
name: String,
campus: {type: mongoose.Schema.Types.ObjectId, ref: 'campus'},
});
module.exports = mongoose.model("School", SchoolSchema, 'school') // i define the existing collection name 'school' to avoid the built in pluralization
When I do school.find() in debugger, I get the mongoose model object. The campus field is missing, and there is an error: ValidatorError: Cannot read properties of undefined (reading 'options')\n at _init
When I alter the Schema to not include campus:
import mongoose from 'mongoose'
const SchoolSchema = new mongoose.Schema({
name: String,
// campus: {type: mongoose.Schema.Types.ObjectId, ref: 'campus'},
});
module.exports = mongoose.model("School", SchoolSchema, 'school')
The debugger now spits out the whole object, including campus but it looks like this:
campus = DBRef {collection: "campus", oid: ObjectId, db: undefined, fields: Object}
There was another configuration where it was spitting it out as if it were creating the object at runtime, new DBref("campus", new ObjectId("...")) or something like that.
When I json it out, it always ends up {$ref: 'campus', $id: ...}. But if I do not include it in the schema, I can't do all that handy populate and things.
I'm this far from extracting the id as a string and doing findById().
Folks, I am STUMPED.
DBRef is a rather controversial convention of data format coming from early versions (doc for v2.2) long before $lookup was added in v3.2. The main reason was to allow cross-database references between documents, yet even then it was not recommended except very niche usecases:
In most cases you should use the manual reference method for connecting two or more related documents. However, if you need to reference documents from multiple collections, consider using DBRefs.
It is not supported by all drivers, caused many problems with export/import because regular field names could not start with $ as recently as in v4.4 https://www.mongodb.com/docs/v4.4/reference/limits/#mongodb-limit-Restrictions-on-Field-Names
Mongoose on the other hand, is quite opinionated ODM which comes with it's own conventions. Automatic opted out from DBRefs in favour of their own Population logic, which is so much incompatible with DBRefs, that they even stopped calling it "DBRef-like" starting from v3.0.
There was an attempt to add support of native DBRefs to mongoose, but the project looks abandoned. You may find it useful to read this explaination: DbRef with Mongoose - mongoose-dbref or populate?
Anyway, apart from DBRefs you will likely face other issues related to mongoose vs spring conventions of document structure. Off the top of my head it's mongoose optimistic locking, which relies on the value of _v field, otherwise not exposed on the application level, etc.
If you intend to use the same database in a heterogeneous setup you can't really use anything but native drivers, as all ODMs come with own conventions and it is very likely they won't match.

Get Schema using collection name mongoose

Lets say I have a collection "employees" in mongodb.now i want to get the
Schema of that collection using "mongoose".Can I do that? I want to have the
schema object from the collection name.
import mongoose from 'mongoose';
public getMappers(collectionName): Schema {
let schema = mongoose.model(collectionName).schema;
return schema ;
}
is there any way to do this?
Short answer: No.
Let me explain why? NoSQL DBs are known for the flexibility of the unknown data fields. One document can have a different set of fields from another sibling document. Due to this, a tool can not determine all the fields in your schema (and ponder that fields can be added later as well). However, You can get a superset of fields by looking at all the documents in your collections and creating a schema out of it.
Mongo compass has a schema tab where you can analyze and use the collection menu to export schema JSON. See below:
You will still need to do a lot of manipulation to create schema out of this JSON, and this JSON isn't meant for creating schema but to understand the kind of data your collection has. e.g. How many docs have this particular field? How many unique values are there for a particular field(cardinality) etc?
Edit 1: I found that the analyzer runs on a subset of docs only not the full collection. We might miss some fields due to that. Read more here

MongoDB lookup ObjectID when the collection it belongs to is unknown?

The software I am currently working with can only run aggregate queries or simple find_one's. I am new to mongodb ,so I am having difficulty figuring out if I can do what I would like to do.
The Question:
Is it possible to run a lookup query on an object id when that object id may be in one of many collections?
The setup:
I have a main collection, this main collection is essentially an array of other ObjectID's that apply to this object. This collection (call it Main_Config) consists of three ObjectID's.
Client
General_Config
Role_Config
The Client, General_Config, and Main_Config can all have an enforced schema I would like the Role_Config to also have an enforced schema. This is where the issue comes into play, the Role_Config, may take 3 or more possible schemas. My idea was to create a collection for every possible schema, however if I do this I will not know to what collection the Role_Config ObjectID belongs to. Is there a way to lookup an ObjectID that may exist in one of many collections?
There is no findInAnyCollection() type of function. In your model you will have to manually code a loop and look it up.
One approach: In your main config collection, we have docs with this field:
otherIds = [ {coll: "ROLE", key: "5fb8057f08c09fb8dfe8d310"}, {coll: "GENERAL", key: "GENERAL_72f2b2922ed98800bd0e"}, ...]
Putting it all together:
db.AA.drop();
db.BB.drop();
db.CC.drop();
db.AA.insert({_id:0, otherIds: [ {coll:"BB", key:0}, {coll:"BB", key:1}, {coll:"CC", key:2}]});
db.BB.insert({_id:0, foo:"bar", baz:"bin"});
db.BB.insert({_id:1, foo:"ion", baz:"kjlkj"});
db.BB.insert({_id:2, foo:"POPPO", baz:"UHUH"});
db.CC.insert({_id:0, data: "wfwefw"});
db.CC.insert({_id:1, data: "jj"});
db.CC.insert({_id:2, data: "mm"});
doc = db.AA.findOne();
doc['otherIds'].forEach(function(item) {
var other = db[item['coll']].findOne({_id:item['key']});
printjson(other);
});

how to create a collection in mongodb and specify the data type for the fields

I am new to nosql i want to create a collection in mongodb .When i saw the tutorials all are teaching about inserting. i am wondering whether we could create a collection with specific data type. example when we create a table in sql we will give the specific data type for that so can we create a collection like that in nosql?
example (SQL)
create table test(
id primary key auto increment,
date_en date
number int);
please help me with this
Thank you,
Actually MongoDB is a schemaless database because of MongoDB is a JSON-style data store. The documents stored in the database can have varying sets of fields, with different types for each field.
But it doesn’t mean that there is no way to define schema. You can define schema as you need for your project. You can use some tools to define your schema like mongoose.
Here I am showing the process of defining schema using mongoose.
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var mySchema= new Schema({
title: String,
date_en: Date,
number: Number
});
module.exports = mongoose.model('collectionname', mySchema);
OR
var mySchema= new Schema({
title: { type: String},
date_en: { type: Date, default: Date.now },
number: {type: Number}
});
module.exports = mongoose.model('collectionname', mySchema);
N.B: according to your collection name will do create table name and mongoose will create _id automatically and unique also so no need to define for id
For more information can visit Mongoose site
I guess this is not possible in mongo db to define schemas.
Please refer to this link from mongo's official documentation.
https://docs.mongodb.com/manual/core/data-modeling-introduction/
"Data in MongoDB has a flexible schema. Unlike SQL databases, where you must determine and declare a table’s schema before inserting data, MongoDB’s collections do not enforce document structure. This flexibility facilitates the mapping of documents to an entity or an object. Each document can match the data fields of the represented entity, even if the data has substantial variation. In practice, however, the documents in a collection share a similar structure."

Why does Mongoose have both schemas and models?

The two types of objects seem to be so close to one another that having both feels redundant. What is the point of having both schemas and models?
EDIT: Although this has been useful for many people, as mentioned in the comments it answers the "how" rather than the why. Thankfully, the why of the question has been answered elsewhere also, with this answer to another question. This has been linked in the comments for some time but I realise that many may not get that far when reading.
Often the easiest way to answer this type of question is with an example. In this case, someone has already done it for me :)
Take a look here:
http://rawberg.com/blog/nodejs/mongoose-orm-nested-models/
EDIT: The original post (as mentioned in the comments) seems to no longer exist, so I am reproducing it below. Should it ever return, or if it has just moved, please let me know.
It gives a decent description of using schemas within models in mongoose and why you would want to do it, and also shows you how to push tasks via the model while the schema is all about the structure etc.
Original Post:
Let’s start with a simple example of embedding a schema inside a model.
var TaskSchema = new Schema({
name: String,
priority: Number
});
TaskSchema.virtual('nameandpriority')
.get( function () {
return this.name + '(' + this.priority + ')';
});
TaskSchema.method('isHighPriority', function() {
if(this.priority === 1) {
return true;
} else {
return false;
}
});
var ListSchema = new Schema({
name: String,
tasks: [TaskSchema]
});
mongoose.model('List', ListSchema);
var List = mongoose.model('List');
var sampleList = new List({name:'Sample List'});
I created a new TaskSchema object with basic info a task might have. A Mongoose virtual attribute is setup to conveniently combine the name and priority of the Task. I only specified a getter here but virtual setters are supported as well.
I also defined a simple task method called isHighPriority to demonstrate how methods work with this setup.
In the ListSchema definition you’ll notice how the tasks key is configured to hold an array of TaskSchema objects. The task key will become an instance of DocumentArray which provides special methods for dealing with embedded Mongo documents.
For now I only passed the ListSchema object into mongoose.model and left the TaskSchema out. Technically it's not necessary to turn the TaskSchema into a formal model since we won’t be saving it in it’s own collection. Later on I’ll show you how it doesn’t harm anything if you do and it can help to organize all your models in the same way especially when they start spanning multiple files.
With the List model setup let’s add a couple tasks to it and save them to Mongo.
var List = mongoose.model('List');
var sampleList = new List({name:'Sample List'});
sampleList.tasks.push(
{name:'task one', priority:1},
{name:'task two', priority:5}
);
sampleList.save(function(err) {
if (err) {
console.log('error adding new list');
console.log(err);
} else {
console.log('new list successfully saved');
}
});
The tasks attribute on the instance of our List model (sampleList) works like a regular JavaScript array and we can add new tasks to it using push. The important thing to notice is the tasks are added as regular JavaScript objects. It’s a subtle distinction that may not be immediately intuitive.
You can verify from the Mongo shell that the new list and tasks were saved to mongo.
db.lists.find()
{ "tasks" : [
{
"_id" : ObjectId("4dd1cbeed77909f507000002"),
"priority" : 1,
"name" : "task one"
},
{
"_id" : ObjectId("4dd1cbeed77909f507000003"),
"priority" : 5,
"name" : "task two"
}
], "_id" : ObjectId("4dd1cbeed77909f507000001"), "name" : "Sample List" }
Now we can use the ObjectId to pull up the Sample List and iterate through its tasks.
List.findById('4dd1cbeed77909f507000001', function(err, list) {
console.log(list.name + ' retrieved');
list.tasks.forEach(function(task, index, array) {
console.log(task.name);
console.log(task.nameandpriority);
console.log(task.isHighPriority());
});
});
If you run that last bit of code you’ll get an error saying the embedded document doesn’t have a method isHighPriority. In the current version of Mongoose you can’t access methods on embedded schemas directly. There’s an open ticket to fix it and after posing the question to the Mongoose Google Group, manimal45 posted a helpful work-around to use for now.
List.findById('4dd1cbeed77909f507000001', function(err, list) {
console.log(list.name + ' retrieved');
list.tasks.forEach(function(task, index, array) {
console.log(task.name);
console.log(task.nameandpriority);
console.log(task._schema.methods.isHighPriority.apply(task));
});
});
If you run that code you should see the following output on the command line.
Sample List retrieved
task one
task one (1)
true
task two
task two (5)
false
With that work-around in mind let’s turn the TaskSchema into a Mongoose model.
mongoose.model('Task', TaskSchema);
var Task = mongoose.model('Task');
var ListSchema = new Schema({
name: String,
tasks: [Task.schema]
});
mongoose.model('List', ListSchema);
var List = mongoose.model('List');
The TaskSchema definition is the same as before so I left it out. Once its turned into a model we can still access it’s underlying Schema object using dot notation.
Let’s create a new list and embed two Task model instances within it.
var demoList = new List({name:'Demo List'});
var taskThree = new Task({name:'task three', priority:10});
var taskFour = new Task({name:'task four', priority:11});
demoList.tasks.push(taskThree.toObject(), taskFour.toObject());
demoList.save(function(err) {
if (err) {
console.log('error adding new list');
console.log(err);
} else {
console.log('new list successfully saved');
}
});
As we’re embedding the Task model instances into the List we’re calling toObject on them to convert their data into plain JavaScript objects that the List.tasks DocumentArray is expecting. When you save model instances this way your embedded documents will contain ObjectIds.
The complete code example is available as a gist. Hopefully these work-arounds help smooth things over as Mongoose continues to develop. I’m still pretty new to Mongoose and MongoDB so please feel free to share better solutions and tips in the comments. Happy data modeling!
Schema is an object that defines the structure of any documents that will be stored in your MongoDB collection; it enables you to define types and validators for all of your data items.
Model is an object that gives you easy access to a named collection, allowing you to query the collection and use the Schema to validate any documents you save to that collection. It is created by combining a Schema, a Connection, and a collection name.
Originally phrased by Valeri Karpov, MongoDB Blog
I don't think the accepted answer actually answers the question that was posed. The answer doesn't explain why Mongoose has decided to require a developer to provide both a Schema and a Model variable. An example of a framework where they have eliminated the need for the developer to define the data schema is django--a developer writes up their models in the models.py file, and leaves it to the framework to manage the schema. The first reason that comes to mind for why they do this, given my experience with django, is ease-of-use. Perhaps more importantly is the DRY (don't repeat yourself) principle--you don't have to remember to update the schema when you change the model--django will do it for you! Rails also manages the schema of the data for you--a developer doesn't edit the schema directly, but changes it by defining migrations that manipulate the schema.
One reason I could understand that Mongoose would separate the schema and the model is instances where you would want to build a model from two schemas. Such a scenario might introduce more complexity than is worth managing--if you have two schemas that are managed by one model, why aren't they one schema?
Perhaps the original question is more a relic of the traditional relational database system. In world NoSQL/Mongo world, perhaps the schema is a little more flexible than MySQL/PostgreSQL, and thus changing the schema is more common practice.
To understand why? you have to understand what actually is Mongoose?
Well, the mongoose is an object data modeling library for MongoDB and Node JS, providing a higher level of abstraction. So it's a bit like the relationship between Express and Node, so Express is a layer of abstraction over regular Node, while Mongoose is a layer of abstraction over the regular MongoDB driver.
An object data modeling library is just a way for us to write Javascript code that will then interact with a database. So we could just use a regular MongoDB driver to access our database, it would work just fine.
But instead we use Mongoose because it gives us a lot more functionality out of the box, allowing for faster and simpler development of our applications.
So, some of the features Mongoose gives us schemas to model our data and relationship, easy data validation, a simple query API, middleware, and much more.
In Mongoose, a schema is where we model our data, where we describe the structure of the data, default values, and validation, then we take that schema and create a model out of it, a model is basically a wrapper around the schema, which allows us to actually interface with the database in order to create, delete, update, and read documents.
Let's create a model from a schema.
const tourSchema = new mongoose.Schema({
name: {
type: String,
required: [true, 'A tour must have a name'],
unique: true,
},
rating: {
type: Number,
default: 4.5,
},
price: {
type: Number,
required: [true, 'A tour must have a price'],
},
});
//tour model
const Tour = mongoose.model('Tour', tourSchema);
According to convetion first letter of a model name must be capitalized.
Let's create instance of our model that we created using mongoose and schema. also, interact with our database.
const testTour = new Tour({ // instance of our model
name: 'The Forest Hiker',
rating: 4.7,
price: 497,
});
// saving testTour document into database
testTour
.save()
.then((doc) => {
console.log(doc);
})
.catch((err) => {
console.log(err);
});
So having both schama and modle mongoose makes our life easier.
Think of Model as a wrapper to schemas. Schemas define the structure of your document , what kind of properties can you expect and what will be their data type (String,Number etc.). Models provide a kind of interface to perform CRUD on schema. See this post on FCC.
Schema basically models your data (where you provide datatypes for your fields) and can do some validations on your data. It mainly deals with the structure of your collection.
Whereas the model is a wrapper around your schema to provide you with CRUD methods on collections. It mainly deals with adding/querying the database.
Having both schema and model could appear redundant when compared to other frameworks like Django (which provides only a Model) or SQL (where we create only Schemas and write SQL queries and there is no concept of model). But, this is just the way Mongoose implements it.