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
],
});
Related
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
I'm making this question since I'm having a hard time asking the right question when I research. I hope to be clear:
I've got 2 Schemas:
Parent [TEAM]:
const EquipaSchema = new mongoose.Schema({
trab1: {
type: Schema.Types.ObjectId,
required: true,
ref: 'Trab'
},
trab2: {
type: Schema.Types.ObjectId,
required: true,
ref: 'Trab'
},
trab3: {
type: Schema.Types.ObjectId,
required: true,
ref: 'Trab'
},
teamName: {
type: String,
required: true
},
marcsEquipa: [{
type: Schema.Types.ObjectId,
ref: 'Marcacao'
}]
},
{collection: 'Equipas'})
And Child [Project]:
const MarcacaoSchema = new mongoose.Schema({
name: { type: String, required: true },
email: { type: String, required: true },
date: { type: Date, required: true},
hour: { type: String, required: true},
type: { type: String, required: true},
address: {type: String, required: true},
state: {type: String, default: 'Pendente'},
// equipa: { type: Schema.Types.ObjectId, ref: 'Equipa' },
equipa: {
type: String,
default: 'Não'
},
cliente: {
type: Schema.Types.ObjectId,
ref: 'User'
},
aval_admin: {
type: String,
default: "Sem Avaliação pelo Manager"
},
descricao: {
type: String,
default: "Sem Descrição"
},
aval_client: {
type: String,
default: "Sem Avaliação do Cliente"
},
avaliado: {
type: Boolean,
default: false
},
team: {
type: Schema.Types.ObjectId,
ref: 'Equipas'
}
},
{collection: 'Marcacao'}
My goal is: When a team is deleted, all of the projects in the team array ['marcsEquipa[]'] get updated to {team: null}, so that I can assign a NEW team to the SAME project.
I've tried using middlewares, but some of its usages are now deprecated and had no success. Whats the correct way to solving this problem?
Thank you in advance
await Marcacao.updateMany({team: req.params._id}, {team: null});
This was the solution. Where req.params._id is the team ID.
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' }});
I have problem with this error when I am creating a new event with category which exists in my database, for example I created an event with category "javascript" and save it to db, and then i tried to create a new event with categories "javascript, html, css" and then i got this error duplicate key error collection
So my schema for event is this:
const EventSchema = new Schema({
title: {
type: String,
required: true,
min: 3,
max: 100
},
featuredImage: {
type: Object,
},
from: {
type: Date,
required: true
},
to: {
type: Date,
required: true
},
location: {
name: {
type: String
},
address: {
type: Object
}
},
description: {
type: String
},
categories: {
type: Array,
trim: true
},
featured: {
type: Boolean
},
created_by: {
type: Schema.Types.ObjectId,
ref: 'User'
},
slug: {
type: String,
default: null
},
registration: {
type: Boolean
},
tickets: [],
allday: {
type: Boolean
},
speakers: [{
type: Schema.Types.ObjectId,
ref: 'User'
}],
attendees: [{
type: Schema.Types.ObjectId,
ref: 'User'
}],
comments: [CommentSchema]
}, {
timestamps: true,
usePushEach: true
});
So basically sending array of strings and i got this error.
You probably have some index defined on categories with the unique flag.
You can list the existing indexes with db.events.getIndexes().
You could drop and recreate the culprit (be careful):
> db.events.dropIndex({categories:1})
> db.events.ensureIndex({categories:1},{sparse:true})
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