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' }});
Related
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;
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
I have added a reply on post comments on my website and now I have a problem how to populate deep reply. I always use this method .populate('comments.authorid', ['username', 'avatarUrl']) but when the user reply on reply, there is a problem.
Do you have any idea how to solve it? I'm looking for something that allows populate all fields by name
Update!
Ok I have found the problem. So in the commentSchema I use comments:[this] It does not work. I need a way to nest CommentSchema in comments field.
const CommentSchema = new Schema({
authorid: {
type: mongoose.Schema.Types.ObjectId,
ref: "Users",
required: true,
},
Date: {
type: Date,
default: Date.now
},
body: {
type: String,
required: true,
minlength: 1,
},
comments:[this],
like:[{
user:{
type: mongoose.Schema.Types.ObjectId,
ref: "Users",
}
}]
});
const userPost = new Schema ({
body: {
type: String,
required: true,
text: true,
minlength: 4,
},
file:{
type: String
},
postTags: [{
type: String
}],
authorid: {
type: mongoose.Schema.Types.ObjectId,
ref: "Users",
required: true,
},
Date:{
type: Date,
default: Date.now
},
like:[{
user:{
type: mongoose.Schema.Types.ObjectId,
ref: "Users",
}
}],
comments: [
CommentSchema.schema
],
});
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
I'm working with Mongodb(mongoose) and node.js (express.js).
The model of DB is:
var messageSchema = new Schema({
_channel: { type: Schema.ObjectId, ref: 'Channel', required: true },
_user : { type: Schema.ObjectId, ref: 'User', required: true },
datetime: { type: Date, required: true },
messageType: { type: String, required: true },
publish: { type: Boolean, default: false },
content: {
title: String,
text: String,
}
});
I want save JSON object inside text field (string).
The JSON object is this:
{ event: 'push',
repository: { id: 53012902, name: 'RestAPI' },
ref: 'refs/heads/master',
commits:
[ { id: 'a10202e5b5157ae5ccd2d77d7d578046693ae404',
url: 'https://github.com/1izpena/RestAPI/commit/a10202e5b5157ae5ccd2d77d7d578046693ae404',
author: '1izpena' } ],
sender: { login: '1izpena', html_url: 'https://github.com/1izpena' } }
I convert this in String, but the result is:
{"event":"push","repository":{"id":53012902,"name":"RestAPI"},"ref":"refs/heads/master","commits":[{"id":"a10202e5b5157ae5ccd2d77d7d578046693ae404","url":"https://github.com/1izpena/RestAPI/commit/a10202e5b5157ae5ccd2d77d7d578046693ae404","author":"1izpena"}],"sender":{"login":"1izpena","html_url":"https://github.com/1izpena"}}
And this result is not a String, I need to keep the same format to parse it later as json object.
Any idea?
Many thanks