mongoose population (refs) is not working - node.js

I have created two models where I am trying to ref one model to another but it's not working and I don't have any idea about it I used it exactly the same way as in the mongoose example but it is not helping, the only difference between my working and their example is I have two different files for both models and I am exporting them to use in another file
The example I took reference from Mongoose
First Model
const userModel = require('./userModel')
const {Schema} = mongoose
const tweet = new Schema({
date: {
type: Date,
required: true,
},
msg:{
type: String,
maxlength:140,
required:true
},
tweetid:{
type: mongoose.Types.ObjectId
}
})
const tweetSchema = new Schema({
user: {
type: Schema.Types.ObjectId,
ref: 'userModel'
},
tweets: {
type: [{tweet}],
default: []
}
})
const tweetModel = mongoose.model('tweet',tweetSchema)
module.exports = tweetModel
Second Model
const {Schema} = mongoose
const userSchema = new Schema({
email: {
type:String,
required: true,
unique: true,
trim:true
},
password: {
type:String,
required: true,
trim:true
},
follows: {
type: [String],
default: []
}
})
const userModel = mongoose.model("User",userSchema)
module.exports = userModel

Your reference string should be equal to the model name that you have passed to mongoose.model:
const tweetSchema = new Schema({
user: {
type: Schema.Types.ObjectId,
ref: 'User'
},
tweets: {
type: [{tweet}],
default: []
}
})

Related

how to populate nested array using mongoose

assuming i have this 2 schemas
company schema with an array of categories
//category
export const CategorySchema = new mongoose.Schema({
name: { type: String },
}, { timestamps: true });
//company
export const CompanySchema = new mongoose.Schema({
user: { type: Schema.Types.ObjectId, ref: 'User' },
name:String,
email:String,
categories:{type: [CategorySchema], default: [] },
}, { timestamps: true });
product schema with category as a ref to the category from company
export const ProductSchema =new mongoose.Schema({
name:String,
category:{ type: Schema.Types.ObjectId, ref: 'Category' },
}, { timestamps: true })
is it possible to populate category from the product ?
i tried this code and it's not working
const products=await this.productModel.find({}).populate({'path':"category","model":"Category"}) ``
what you need is just
productModel.find({}).populate("category")
try this code for populate
const products=await this.productModel.find({}).populate({'path':"category","model":"company.categories"})

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

How can i display products per each category stored in MongoDB

currently i created a schema for storing products using mongoose as below
const Schema = mongoose.Schema;
const ProductSchema = new Schema({
title: {
type: String,
required: true
},
price: {
type: Number,
required: true
},
description: {
type: String,
required: true
},
quantity: {
type: Number,
required: true
},
manufacture: {
type: String,
required: true
},
creator: {
type: Schema.Types.ObjectId,
ref: 'user'
},
category: {
type: Schema.Types.ObjectId,
ref: 'category'
}
});
module.exports = { Product: mongoose.model('product', ProductSchema) };
and here another schema for storing categories that products are related to
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const CategorySchema = new Schema({
title: {
type: String,
required: true
}
});
module.exports = { Category: mongoose.model('category', CategorySchema) };
each product is related to a category
the question is how can i display all products that are related to a specific category.
i tried .find() method but i can't use it correctly.
thanks for any advice
You need to use .populate('category'), after .find() in order to populate all the connected data.
products.find().populate('category').exec((err, product) => { })

mongoose schema , Invalid schema configuration

i have a schema of user that contain an array of movie
i create a new schema of Movie
but i get error of invalid schema configuration.
what i'm doning worng?
enter code here
const mongoose = require("mongoose");
const Movie = require("./movie-model");
const Schema = mongoose.Schema;
const User = new Schema({
firstName: { type: String, required: true },
lastName: { type: String, required: true },
email: { type: String, required: true },
password: { type: String, required: true },
movies: { type: Movie },
});
module.exports = mongoose.model("user", User);
var mongoose = require("mongoose");
var Schema = mongoose.Schema;
var Movie = new Schema(
{
name: { type: String, required: true },
time: { type: String, required: true },
rating: { type: Number, required: false },
priorety: { type: Number, required: true },
},
);
module.exports = mongoose.model("movie", Movie);
in movie-model
module.export = Movie
instead of
module.exports = mongoose.model("movie", Movie);
User has many movies
const mongoose = require("mongoose");
const Movie = require("./movie-model");
const Schema = mongoose.Schema;
const User = new Schema({
firstName: { type: String, required: true },
lastName: { type: String, required: true },
email: { type: String, required: true },
password: { type: String, required: true },
movies: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "movie",
},
],
});
module.exports = mongoose.model("user", User);
I invite you to read more about One-to-Many Relationships with Embedded Documents
You need to done referencing in User collection
movies: [
type: mongoose.Schema.ObjectId,
ref: 'user'
]
//instead of doing that
movies: { type: Movie },

How do I index a field on a mongoose Schema that uses a discriminator?

The error started after I started using the discriminator.
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const Base = require("../config/Base");
const Refill = Base.discriminator(
"Refill",
new Schema({
cylinderSize: { type: Number, required: true },
cylinderSwap: { type: Boolean, required: true },
quantity: { type: Number, required: true },
location: {
type: { type: String },
coordinates: [Number]
}
})
);
Refill.index({ location: "2dsphere" });
module.exports = mongoose.model("Refill");
This returns the error Refill.index is not a function
In Mongoose, indexes must be created on schemas, not models. In your case, the Refill object is a model. One approach is to implement this in three steps:
Create the schema
Add the index to the schema
Create the model
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const Base = require("../config/Base");
const refillSchema =
new Schema({
cylinderSize: { type: Number, required: true },
cylinderSwap: { type: Boolean, required: true },
quantity: { type: Number, required: true },
location: {
type: { type: String },
coordinates: [Number]
}
});
refillSchema.index({ location: "2dsphere" });
const Refill = Base.discriminator("Refill", refillSchema);
module.exports = mongoose.model("Refill");
I just took out the Refill.index({ location: "2dsphere" }); and the rest of my code is working fine apparently indexing that field wasn't necessary.

Resources