How to put collection name in mongoose model - node.js

mY model,
var CategorySchema = new Schema({
categoryname: {
type: String
},
topictitle: {
type: String
},
topicdescription: {
type: String
},
tag: {
type: String
},
topicid: {
type: Schema.ObjectId
},
user: {
type: Schema.ObjectId,
ref: 'User'
}
});
mongoose.model('topics', CategorySchema);
Here topics is the name of my model but where can i keep my collection name?Can anyone suggest me help.

In the below model definition
mongoose.model('topics', CategorySchema);
var topics = mongoose.model('topics', CategorySchema,'topics' );
var tags = mongoose.model('tags', TagSchema, 'topics');
'topics' (last parameter) is the collection name & CategorySchema is the structure of a particular document
Check Mongoose documentation

Related

How to define schema for personal collection with different type of items with Mongoose and Nodejs

I am creating personal collection web app in which users can create their own collection including different item such as books, whiskey, poststamps... etc. I created schema for this but now i realised i created only for items not for collections. So i need some help to define my collections schema in which users can create different items and some properties of item should be changeable because of item type.For example, I want to store a book collection. I can select (add to standard set of id+name+tags) additional string field “Author”, additional text field “Synopsis”, addition data field “Publication Year”. Maybe with Whiskey or another collection
Here is my DB structure:
User Schema
import mongoose from "mongoose";
const { Schema, model } = mongoose;
import bcrypt from "bcrypt";
const userSchema = new Schema(
{
username: { type: String },
email: { type: String, unique: true},
password: { type: String },
role: { type: String, enum:["user", "admin"], default:"user"},
status: {type: String, default:"active"},
collections: [{ type: Schema.Types.ObjectId, ref: 'Collection' }]
},
{ timestamps: true }
);
Collection schema
import mongoose from "mongoose";
const { Schema, model } = mongoose;
const collectionSchema = new Schema(
{
name: { type: String },
description: { type: String },
topic: { type: String },
comments:[{
user: { type: Schema.Types.ObjectId, ref: 'User', required: true },
text: String,
}],
user: [{ type: Schema.Types.ObjectId, ref: "User" }],
likes:[{ type: Schema.Types.ObjectId, ref: 'User' }],
},
{ timestamps: true }
);
collectionSchema.index({'$**': 'text'});
export default model("Collection", collectionSchema);

How to populate a data for a field in mongoose, where reference is a nested array in model?

How can I populate category in courses model?
I have courses, courses will have category from categories->subcategories model.
I don't know how to populate from nested objects.
Reference model is category, I have to populate from array subcategories!
**courses:**
const CourseSchema = new mongoose.Schema({
userId: {
type: mongoose.Schema.Types.ObjectId,
ref: 'users'
},
name: {
type: String
},
description: {
type: String
},
category: {
type: mongoose.Schema.Types.ObjectId,
ref: 'category'
}
});
**category:**
const mongoose = require("mongoose");
const CategorySchema = new mongoose.Schema({
userId: {
type: mongoose.Schema.Types.ObjectId,
ref: 'users'
},
name: {
type: String,
required: true
},
subcategories: [{
name: {
type: String
}
}]
});
const Category = mongoose.model('category', CategorySchema);
module.exports = Category;
use seprate collection for subCetagory like:
**courses**
const CourseSchema = new mongoose.Schema({
userId: {
type: mongoose.Schema.Types.ObjectId,
ref: 'users'
},
name: {
type: String
},
description: {
type: String
},
category: {
type: mongoose.Schema.Types.ObjectId,
ref: 'SubCategory'
}
});
**SubCategory:**
const mongoose = require("mongoose");
const SubCategorySchema = new mongoose.Schema({
name: {
type: String,
required: true
},
categorie: {
type: String,
ref: "category"
}
});
const SubCategory = mongoose.model('category', SubCategorySchema);
module.exports = SubCategory;
**Category**
const mongoose = require("mongoose");
const CategorySchema = new mongoose.Schema({
userId: {
type: mongoose.Schema.Types.ObjectId,
ref: 'users'
},
name: {
type: String,
required: true
},
subcategories: [
{
type: Schema.types.objectId,
ref: "SubCategory"
}
]
});
then just add subcetagory id to course when insert new course or update a course and when you want to get course along with subcetagory and category use populate query of mongoose

Mongoose fetch data from collection A if it's reference exists on collection B

I need your help please with a mongoose query for my express app.
I have 3 collections Movies, TvShows and Trailers and I need to fetch all movies or shows that have trailers.
here are the models:
var TrailerSchema = new Schema(
{
link: {
type: String,
required: true,
},
movieId: { type: mongoose.Schema.Types.ObjectId, ref: 'Movie' },
showId: { type: mongoose.Schema.Types.ObjectId, ref: 'Show' },
}
)
module.exports = mongoose.model('Trailer', trailerSchema)
const mongoose = require('mongoose')
const Schema = mongoose.Schema
var movieSchema = new Schema(
{
title: {
type: String,
required: true,
},
rating: {
type: Number,
},
}
)
module.exports = mongoose.model('Movie', movieSchema)
in the Trailer collection there are some documents with the movieId field and some with showId.
Now how can I fetch all the movies or shows that have trailers?
because you just stored movieId in TrailerSchema and movieSchema don't have field like TrailerId:[{type: mongoose.Schema.Types.ObjectId, ref: 'Trailer'}], can not use populate...
but for your issue at first
let listOfIds = await Link.find( { movieId: { $exists: true } }, 'movieId._id' ).lean()
I don't know real data stored in Trailer collection for query in Trailer.find after get IDs you should search in Movie collection to get all info
let listOfMovies = await Movie.find({ _id: { $in: listOfIds.map((id) => {if(id.movieId) return id.movieId._id} ) }, })

How can i query the data in a sub-document of a document from a sub-document of another document

This is my category schema. For every category document, there is a subdocument of subcategories
#category schema
const CategorySchema = mongoose.Schema({
name: {
type: String, required: true
},
subcategories: [{
name: {
type: String, required: false
},
}],
created : {
type : Date,
default: Date.now()
}
});
let Categories = mongoose.model('categories', CategorySchema);
# selected category schema
const BusinessCategoriesSchema = mongoose.Schema({
business_id: {
type: String
},
category_id: {
type: mongoose.Schema.Types.ObjectId,
ref: "categories",
required: true
},
subcategories: [{
subcategory_id: {
type: mongoose.Schema.Types.ObjectId,
ref: "subcategories._id",
required: false
}
}]
});
let businessCategories = mongoose.model('business-categories', BusinessCategoriesSchema);
How can I retrieve the subcategories sub-document from Categories schema when I perform a query on business-categories collection?
#This is the code snippet I am using but am not getting my desired result
const query = await businessCategories.find({business_id : businessId })
.populate('category_id')
.populate('subcategories.subcategories_id');
I know I am not doing something right.
I was able to get the category name from categories schema but I could not get the subcategories sub-document from the categories schema.
Thank you in advance

Embedding another mongoose schema

I'm trying to embed a model in a mongoose schema. Here's what I have:
const People = {
userId: {
type: mongoose.Schema.Types.objectId,
required: true,
ref: 'User'
},
locationId: {
type: mongoose.Schema.Types.objectId,
required: true,
ref: 'Location'
},
};
const Person = mongoose.model(
'Person',
new mongoose.Schema({
...People,
gender: {
type: String
}
})
);
const shmanian = await new Person({gender: 'other', userId:'someUserId', locationId: 'someLocationId'}).save();
The response I get is {gender: 'other'}
The problem is that people doesn't get populated when I create Person.
You should embed an array of "Person" inside a model "People". For example,
const Schema = require("mongoose").Schema;
const model = require("mongoose").model;
const Person = new Schema({
userId: {
type: mongoose.Schema.Types.objectId,
required: true,
ref: 'User'
},
locationId: {
type: mongoose.Schema.Types.objectId,
required: true,
ref: 'Location'
},
});
const People = new Schema({
person: [Person]
});
module.exports = model("People", People);
Here, everytime you create a new Person, you can add it to the People model which contains an array of Person objects.
Not a mongoose Problem.
People is undefined when you create the Object Person.
Thus it doesn't get populated.
Try switching both assignments.

Resources