How to find and populate reference object fields in a mongoose schema - javascript

I'm trying to fetch data from below mongoose schema, But I'm not sure how to fetch the role field, which is a type of RoleObject.
import * as mongoose from 'mongoose';
const Schema = mongoose.Schema;
const RoleObject = {
current_role: {
type: Schema.Types.ObjectId,
ref: 'Role',
autopopulate: true
},
new_role: {
type: Schema.Types.ObjectId,
ref: 'Role',
autopopulate: true
}
}
const UserRequestSchema = new mongoose.Schema({
group: {
type: Schema.Types.ObjectId,
ref: 'Group',
autopopulate: true,
required: true
},
user: {
type: Schema.Types.ObjectId,
ref: 'User',
autopopulate: true,
required: true
},
role: {
type: RoleObject
},
status: {
type: String,
required: true,
enum: ['pending', 'approved', 'denied']
},
type: {
type: String,
required: true,
enum: ['group-join', 'role-change']
},
active: {
type: Boolean,
required: true
}
});
UserRequestSchema.index( { group: 1, user: 1 }, { unique: true } );
export { UserRequestSchema };
Here I want populate the role field from the UserRequestSchema, which is given as RoleObject.
Is it possible through populate the field using find method or do I need to use aggregation ?

Try this
UserRequest.find({active:true}).populate({
path: 'role.current_role role.new_role',
model: 'Role',
select: 'name'
}).exec((error, result) => {
if (error) {
console.log(error, " ERROR")
}
console.log(result, "Result")
});
If you face any issue. Please let me know

Related

How to show categories name with mongodb relationships

i wanna show categories name in that view who users can see it beside product
actually in single page view of product but i think i have some problems in relationships of mongo because it just return an empty array!
i will appreciate if you help me
product model :
const createProductSchema = Schema(
{
user: { type: Schema.Types.ObjectId, ref: "User" },
categories: [{ type: Schema.Types.ObjectId, ref: "Category" }],
title: { type: String, required: true },
type: { type: String, required: true },
slug: { type: String, required: true },
body: { type: String, required: true },
images: { type: Object, required: true },
thumb: { type: String, required: true },
price: { type: String, required: true },
tags: { type: String, required: true },
viewCount: { type: Number, default: 0 },
},
{ timestamps: true, toJSON: { virtuals: true } }
);
createProductSchema.virtual("category", {
ref: "Category",
localField: "_id",
foreignField: "products",
});
category model :
const categorySchema = Schema(
{
products: [{type: Schema.Types.ObjectId, ref: "Product" }],
name: { type: String, required: true },
slug: { type: String, required: true },
parent: { type: Schema.Types.ObjectId, ref: "Category", default: null },
},
{ timestamps: true, toJSON: { virtuals: true } }
);
productController:
let product = await Product.findOne({ slug: req.params.product })
.populate([
{
path: "user",
select: "name",
},
{
path:"category",
select:"name",
}
]);
res.json(product);
and in output i just can see category:[]
:((((((
You should populate categories, not category:
let product = await Product.findOne({ slug: req.params.product })
.populate([
{
path: 'user',
select: 'name',
},
{
path: 'categories',
select: 'name',
},
])
.exec();
res.json(product);

Mongo DB - MissingSchemaError

I am working with mongo DB and mongoose and I'm getting the following error when running the code below.
"MissingSchemaError: Schema hasn't been registered for model "Project".\nUse mongoose.model(name, schema)"
import {...}
const { school } = request.params;
const document = await Document.find({
}).populate('project').lean();
if (document.project.school != school)
throw HTTP.forbidden('ERROR.DOCUMENT_DOES_NOT_BELONG_TO_YOUR_SCHOOL');
My schemas look as follows
const Document = new Schema({
name: { type: String },
type: { type: String },
project: {
type: Schema.Types.ObjectId,
ref: 'Project'
}
}, {
timestamps: true
});
const Project = new Schema({
name: { type: String },
school: {
type: Schema.Types.ObjectId,
ref: 'School'
}
}, {
timestamps: true
});
const School = new Schema({
name: { type: String },
curriculum: [{
type: Schema.Types.ObjectId,
ref: 'Curriculum'
}],
}, {
timestamps: true
});
Does anyone know what I need to do to overcome this everything has been initialised by the time this section of code is getting called?
Assuming you have created model for each schema, try writing your refs using lowercase:
const Document = new Schema({
name: { type: String },
type: { type: String },
project: {
type: Schema.Types.ObjectId,
ref: 'project'
}
}, {
timestamps: true
});
const Project = new Schema({
name: { type: String },
school: {
type: Schema.Types.ObjectId,
ref: 'school'
}
}, {
timestamps: true
});
const School = new Schema({
name: { type: String },
curriculum: [{
type: Schema.Types.ObjectId,
ref: 'curriculum'
}],
}, {
timestamps: true
});

i want to check if current user is following other user

i want to check if current user is following other use lets say check if user A is following user B.
User Model:-
const UserSchema = new Schema({
email: {
required: true,
type: String,
unique: true,
lowercase: true,
validate: (value) => {
if (!validator.isEmail(value)) {
throw new Error('Invalid email address.');
}
}
},
fullName: {
required: true,
type: String,
},
username: {
required: true,
type: String,
unique: true,
lowercase: true,
minlength: 3,
},
password: {
type: String,
minlength: 8,
},
avatar: String,
bio: {
type: String,
default: null,
maxlength:300,
},
location: {
type: String,
default: 'Bangalore'
},
website: {
type: String,
default: null,
},
joindate: {
type: Date,
default: new Date()
},
isVerified:{
type:Boolean,
default:false,
}
})
const UserModel = mongoose.model('User', UserSchema);
module.exports = UserModel;
Followings Model:-
const FollowingsSchema = new Schema({
user: {
ref: 'User',
unique:true,
type: Schema.Types.ObjectId,
},
followings: [{
user: {
type: Schema.Types.ObjectId,
ref: 'User'
}
}]
})
const Followings = mongoose.model('Followings', FollowingsSchema);
module.exports = Followings;
Followers Model:-
const FollowersSchema = new Schema({
user: {
ref: 'User',
unique:true,
type: Schema.Types.ObjectId,
},
followers: [{
user: {
type: Schema.Types.ObjectId,
ref: 'User'
}
}]
})
const Followers = mongoose.model('Followers', FollowersSchema);
module.exports = Followers;
currently i was able to achieve this by iterating through each follower and check if user exist in that user followers list.
i want to achieve this with mongodb aggregation ,im new to mongob

Mongoose querying an array of objects

How to querying an array using Mongoose ?
search Schema:
const searchschema = new schema({
yeardate: { type: Number, required: true, min: 1820 },
word: { type: String, required: true, index: true },
user: [{ type: schema.Types.ObjectId, ref: 'User' }] })
user Schema:
const userschema = new schema({
username: { type: String, required: true, unique: true, index: true },//
name: { type: String, default: 'NoName' },
gender: { type: String, default: 'male' }, })
This is the query I have tried but did not work:
searchmodel.paginate({ 'user': { $elemMatch: { gender: 'female' } } }, { page: page, limit: 5, populate: ['user'] }).then(searches => {
if (!searches) {
return res.json({ message: 'there is no search' })
}else {
return res.json(searches)
}
})

Get parent data based reference ID on Node.js and MongoDB

I am trying to get products data based on orders products id and below is my Order Model
import mongoose from 'mongoose';
const { ObjectId, String, Number } = mongoose.Schema.Types;
const OrderSchema = new mongoose.Schema({
user: {
type: ObjectId,
ref: "User"
},
products: [
{
quantity: {
type: Number,
default: 1
},
product: {
type: ObjectId,
ref: "Product"
}
}
],
email: {
type: String,
required: true
},
total: {
type: Number,
required: true
},
status: {
type: String,
required: true,
default: 'pending',
enum: ["pending", "delivered"]
}
},{
timestamps: true
});
export default mongoose.models.Order || mongoose.model("Order", OrderSchema);
The Product Model:
import mongoose from 'mongoose';
const { String, Number } = mongoose.Schema.Types;
const ProductSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
price: {
type: Number,
required: true
},
productType: {
type: String,
required: true
},
sku: {
type: String,
unique: true
},
description: {
type: String,
required: true
},
mediaUrl: {
type: String,
required: true
}
},{
timestamps: true
});
export default mongoose.models.Product || mongoose.model('Product', ProductSchema);
And the query is like below for all orders:
const orders = await Order.find()
.sort({ createdAt: 'desc' })
.populate({
path: "products.product",
model: "Product"
});
// console.log(orders)
res.status(200).json({ orders });
The concept is when creating an order it's creating with product id and I want to fetch the products based on the order product id.
And this way it showing
MongooseError [MissingSchemaError]: Schema hasn't been registered for model "Product".
How can I solve that?
Thanks
In the Order model you might be import the Product model then in the ref you use without quotation like
ref: Product
That is the way I think.
Thanks

Categories