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

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

Related

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

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

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
});

How to get following users posts from mongodb

hi I'm using React with mongoDB I'm new to the mongoDB. I guess My schemas is having problems
how do I get posts that I'm following users. I've been facing this problem for a week
I can get All the posts of my following users, I think it might be unnecessary I'd like to just get lastest 10 posts of my following users
if there is a tip to get posts please let me know thanks for reading this question
Here's my Post Schema
import mongoose from "mongoose";
const postSchema = mongoose.Schema({
title: String,
message: String,
name: String,
tags: [String],
picture: String,
likes: {
type: [String],
default: [],
},
createdAt: {
type: Date,
default: new Date(),
},
profilePicture: String,
userId: String,
comments: {
type: [
{
commentUserId: String,
commentUserName: String,
comment: String,
createdAt: Date,
},
],
},
});
const Post = mongoose.model("Post", postSchema);
export default Post;
Here's User Schema
import mongoose from "mongoose";
import bcrypt from "bcrypt";
const userSchema = mongoose.Schema({
name: { type: String, required: true },
email: { type: String, required: true, unique: true },
password: { type: String, required: true },
id: { type: String },
profilePicture: {
type: String,
default:
"https://icon-library.com/images/anonymous-avatar-icon/anonymous-avatar-icon-25.jpg",
},
isAdmin: {
type: Boolean,
required: true,
default: false,
},
userPosts: [
{
_id: String,
title: String,
picture: String,
message: String,
tags: [String],
name: String,
profilePicture: String,
userId: String,
likes: [String],
comments: [
{
commentUserId: String,
commentUserName: String,
comment: String,
createdAt: Date,
},
],
},
],
following: {
type: [String],
default: [],
},
followers: {
type: [String],
default: [],
},
notifications: [
{
_id: mongoose.Schema.Types.ObjectId,
sender: String,
notificationType: String,
read: Boolean,
},
],
});
const User = mongoose.model("User", userSchema);
export default User;

Why am I getting 'Maximum call stack size exceeded' error?

Beginner here, and I dont understand why I am getting max call stack error:
app.post('/farms/:id/products', async (req, res) => {
const { id } = req.params;
const farm = await Farm.findById(id);
const { name, price, category } = req.body;
const newProduct = new Product({ name, price, category });
newProduct.farm = farm;
farm.products.push(newProduct);
res.send(farm)
})
I noticed if I swap to this, I no longer get the error. However, I don't understand why this would work.
farm.products.push(newProduct);
newProduct.farm = farm;
Here is how I defined the Product schema:
const productSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
price: {
type: Number,
required: true,
min: 0
},
category: {
type: String,
lowercase: true,
enum: ['fruit', 'vegetable', 'dairy']
},
farm: {
type: Schema.Types.ObjectId,
ref: 'Farm'
}
})
const Product = mongoose.model('Product', productSchema);
Here is how I defined the Farm schema:
const farmSchema = new mongoose.Schema({
name: {
type: String,
required: [true, 'Farm must have a name!']
},
city: {
type: String
},
email: {
type: String,
require: [true, 'Email is required!']
},
products: [{
type: Schema.Types.ObjectId,
ref: 'Product'
}]
})
const Farm = mongoose.model('Farm', farmSchema);

How to using "find()" with populate field in mongoose?

I have 2 collection in same db. I need to using find() to select only "Events" that have "team" equal "team1"
Thank you very much.
I have try to find by population field but it doesn't work.
This is my Event schema
const Event = mongoose.model('Event', new mongoose.Schema({
title: {
type: String,
required: true,
min: 3
},
eventType: {
type: String,
lowercase: true
},
date: {
type: Date,
default: Date.now()
},
venue: String,
country: String,
callLog: {
type: String,
max: 1000
},
eventImgUrl: [String],
editedBy : {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
},
timestamp: {
type: String,
default: Date.now()
}
}));
This is my User schema
const User = mongoose.model('User', new mongoose.Schema({
username: {
type: String,
required: true,
min: 3,
lowercase: true
},
name: String,
email: String,
team: String,
role: {
type: String,
enum: ['admin', 'creator', 'viewer']
}
}));
This is my Controller
const events = await Event.find()
.populate({ path: 'editedBy', select: ['name', 'team']});
res.send(events);
To find all Events that have a team of "team1":
const team1Events = await Event.find({ team: "team1" });
select just specifies the fields returned. You need to use populate match:
await Event.find()
.populate({ path: 'editedBy', match: { yourField: 'yourmatch' }});

Categories