How to load mongoose Schema from the collection name - node.js

Ideally, for populate to work during queries in mongoose, both the schemas of that which is been populated and the calling schema needs to be imported in same file under same repo.
Now, I have a scenario where a schema called AuthorSchema was created by another internal micro-service in another repo which is pointing to the same database as my own service and I wish to populate it during my queries.
Is there a way to automatically decode the AuthorSchema from the author collection name after I've connected to the database?
E.g
let posts = await Post.find({})
.populate("author", 'first_name last_name _id').limit(10)
Where I have created postSchema in my own service but authorSchema was created by another micro-service in another repo called author-management-microservice and as such I have no access to that schema.
What I would want is something like:
let AuthorSchema = mongoose.connection.decodeSchemaFromCollectionName('author');
Such that I can modify my query to something like
let posts = await Post.find({})
.populate({path:"author", model:AuthorSchema, select:'first_name last_name _id'}).limit(10)
The reason I want something like this is because I have been battling with MissingSchemaError: Schema hasn't been registered for model "Author". whenever I try to populate author and I don't want to copy around duplicate schema files across different micro-services.

To get the schema from a registered Mongoose model, you need to access the schema specifically:
const AuthorSchema = require('mongoose').model('Author').schema;

Is there a way to automatically decode the AuthorSchema from the author collection name after I've connected to the database?
No - the schema is saved at the code level, not the database level. There is no way to know the schema just from connecting to the database.

Related

How to create new Schema same as an existing one in mongoDB

I have a question in mongoDB. I have a user schema with different fields and methods. But I want to when deleting a user from this schema to place it in another schema for example deleted-users schema.
Should I create the deleted-users schema with the same exact fields but different name ?
Or is there a better way to this

One to one relationships in mongodb with mongoose

I have 2 databases named Users and Links. Whenever a new user signup, one collection is created in Users with unique id. What I want is to create another collection in Links with a field userId that has id of the newly created user. Also I want the id of the new collection from Links to be added in the newly created user collection. How can I achieve this with mongoose and mongodb?
What I understood was to write 3 queries as follows:
const user = await User.create({req.body}) //comes from the client side
const link = await Link.create({userId: user._id})
const updatedUser = await User.findOneAndUpdate({_id: user._id}, {link: link._id})
What I want to know, Is this the correct way?
It's not directly answering your question but you might want to reconsider your choice of database types. Since you're talking about querying by keys across multiple tables where records have some kind of relationship you might want to have a look at relationship databases like PostgreSQL for instance.

Why use mongoose schema in Node.js

I was learning Node.js and Mongoose. Then, I cam across the term schema which is defined as the description of the structure of the data, default values and validation. So, as we know schema looks basically like this:
var TaskSchema = new Schema({
name: String,
priority: Number
});
The question I would like to ask is Why should we care about the description of structure of data that the schema allows to achieve, I mean, what is the main point in the use of schemas in mongoose? if you say, validation, then can't we achieve that with express-validator package? or...
Everything in Mongoose starts with a Schema. Each schema maps to a MongoDB collection and defines the shape of the documents within that collection.
See the documentation for more information.
Schemas not only define the structure of your document and casting of properties, they also define document instance methods, static Model methods, compound indexes, and document lifecycle hooks called middleware.
This is what allows you to communicate with the database easily using mongoose. It's not just for validation.

How to retrieve schema from a mongoose collection?

using this line :
var collection = mongoose.connection.db.collection("users");
I get users s collection, now i need to get the schema from that collection ?
Is there a way to do this? thank you.
PS: I dont have any models
if you do not have any models, I'm afraid this can't be done.
the schema is the structural representation of the document, not the collection. You can use the schema (via the model) to enforce that any document added to the collection match some structure, but there's nothing that prevents you from inserting into this collection a different document without this model, that will not match the criteria
so the schema does not live in the DB, it is a part of the mongoose module, and lives in the code. and the way to access it is through the model only

Mongoose access multiple collection

In mongodb I have one collection named as People.
It contains:
_id:Number,
name:String,
friends:[{friendsId:{type:Schema.Types.ObjectId,ref:'People'},addedTime: Date}]
I want to search a name of friend of a particular user and return the _id of that friend in a single query using mongoose in node.js.
Its impossible to retrieve the data in a single query/populate. Since mongodb is not a relational database. Iterate the data separately & give the result as callback to next query.

Resources