NodeJs How can i show first 3 authors in my model? - javascript

I made a simple api. With 3 tables.(collections with mongodb). Like Collections-Authors-Articles. I want to show 3 author on collections but i cant found how can i do it ? When i send get request to collections on postman i need to see like;
"name":xxx;
"icon":xxx;
"authors":{
authorid,
authorid,
authorid }
My Schemes :
article.js =
const { db } = require("../collection");
const mongoose = require("mongoose"),
Schema = mongoose.Schema;
var Articles = Schema({
author: {
type: Schema.Types.ObjectId,
ref: "Authors",
},
collectionid: {
type: Schema.Types.ObjectId,
ref: "Collections",
},
name: {
type: String,
required: true,
},
content: {
type: String,
required: true,
},
createddate: {
type: Date,
default: Date.now,
},
updateddate: {
type: Date,
default: Date.now,
},
});
module.exports = mongoose.model("Articles", Articles);
author.js =
const mongoose = require("mongoose"),
Schema = mongoose.Schema;
var Authors = Schema({
name: {
type: String,
required: true,
},
avatar: {
type: String,
required: true,
},
});
module.exports = mongoose.model("Authors", Authors);
collections.js =
const mongoose = require("mongoose"),
Schema = mongoose.Schema;
var Collections = Schema({
name: {
type: String,
required: true,
},
icon: {
type: String,
required: true,
},
});
module.exports = mongoose.model("Collections", Collections);

You can use populate to populate collection authors, see the mongoose docs

Related

Mongoose Schema cannot be identified by code

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
//broken schema
var coursesSchema = new Schema({
college: {
type: String,
required: true
},
units: {
type: Number,
required: true
},
course_code: {
type: String,
required: true
},
course_name: {
type: String,
required: true
},
class_number: {
type: String,
required: true
},
section: {
type: String,
required: true
},
class_day: {
type: String,
required: true
},
time_start: {
type: String,
required: true
},
time_end: {
type: String,
required: true
},
faculty: {
type: String,
required: true
}
});
module.exports = mongoose.model('Courses', coursesSchema);
//working schema
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var loaSchema = new Schema({
process_name: {
type: String,
required: true
},
process_details: {
type: String,
required: true
},
process_deadline: {
type: String,
required: true
},
});
module.exports = mongoose.model('LOA', loaSchema);
I have this schema which I export into index.js file. This schema works in other parts of the code except in index.js. When I query Courses schema, it returns model.find() is not a function. When I try creating a new Courses object it says Constructor is not a schema. I have other schemas that work fine inside index.js and I get to query them, but this schema is an exception.
Does anyone know the reason behind this?
index.js is the special file and actually it's root of your module, it's better separate the schema from that to prevent from bugs

Mongoose getting the error: MissingSchemaError: Schema hasn't been registered for model

I am getting this error and can't figure it out. I HAVE NAMED THE REF EXACLTY AS THE MODEL:
MissingSchemaError: Schema hasn't been registered for model "ParticipantStatus".
Here are my models:
ParticipantStatus model:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const participantStatusSchema = new Schema({
_id: {
type: Number,
required: true,
},
name: {
type: String,
required: true,
},
});
module.exports = mongoose.model('ParticipantStatus', participantStatusSchema);
EventParticipant model:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const eventParticipantSchema = new Schema(
{
userId: {
type: Schema.Types.ObjectId,
ref: 'User',
required: true,
},
eventId: {
type: Schema.Types.ObjectId,
ref: 'Event',
required: true,
},
teamId: {
type: Schema.Types.ObjectId,
ref: 'Team',
},
statusId: {
type: Number,
ref: 'ParticipantStatus',
required: true,
},
isActive: {
type: Boolean,
required: true,
default: true,
},
},
{ timestamps: true }
);
module.exports = mongoose.model('EventParticipant', eventParticipantSchema);
This is the code where the error is thrown, when i try to get event participants and populate statusId(ParticipantStatus):
let participants = await EventParticipant.find(
{
eventId: req.params.eventId,
isActive: true,
},
{ _id: false }
)
.populate('userId', 'email')
.populate('statusId')
.select('userId');
I have been stuck for hours on this. Only the .populate('statusId') part throws the error, the rest works well. Thanks in advance
type of field that you want to populate based on should be ObjectId so change the type of statusId from Number to Schema.Types.ObjectId like this:
statusId: {
type: Schema.Types.ObjectId,
ref: 'ParticipantStatus',
required: true,
}
Well the problem was that u need to import:
const ParticipantStatus = require('../models/participantStatus.model');
even if you do not REFERENCE IT DIRECTLY in your code, which is really strange in my opinion.
Hope this helps anyone.

Populate many subdocument levels down in mongoose

I'm creating a comment system where a comment can have subComments (when you comment on a comment). I can say how many levels deep I want to populate the subComments, but I don't know how many there are in advance. Is there a way to tell mongoose to just keep populating the subComments of already populated comments until there are no more subDocuments?
CommentModel.js
const mongoose = require("mongoose");
const schema = mongoose.Schema;
const commentSchema = new schema(
{
post: { type: schema.Types.ObjectId, required: true, ref: "post" },
content: { type: String, required: true },
votes: { type: Number, required: true },
user: { type: schema.Types.ObjectId, required: true, ref: "user" },
subComments: [{ type: schema.Types.ObjectId, ref: "comment" }],
parentComment: { type: schema.Types.ObjectId, ref: "comment" },
},
{ timestamps: true }
);
module.exports = Comment = mongoose.model("comment", commentSchema);
PostRouter.js
router.get("/full/:postId", async (req, res) => {
const postId = req.params.postId;
const post = await Post.findById(postId).populate({
path: "comments",
populate: {
path: "subComments",
},
// how can i populate infinitely down in the path subComments?
});
res.json(post);
});
Please check the graph lookup feature: https://docs.mongodb.com/manual/reference/operator/aggregation/graphLookup/
Example with arrays can be found here: https://www.oodlestechnologies.com/blogs/how-to-use-graphlookup-in-mongodb/

Still getting "Schema is not a constructor", despite properly importing and exporting my Schema

Here is my code. I have a review schema in a separate file called "review.js".
const express = require('express');
const mongoose = require('mongoose');
const User = require('../model/user');
require('mongoose-currency').loadType(mongoose);
const Currency = mongoose.Types.Currency;
const Schema = mongoose.Schema;
let reviewSchema = new Schema();
reviewSchema.add({
rating: {
type: Number,
min: 1,
max: 5,
defualt: 0
},
howEasyToMake: {
type: Number,
required: true,
min: 1,
max: 5
},
howGoodTaste: {
type: Number,
required: true,
min: 1,
max: 5,
},
wouldMakeAgain: {
type: Number,
required: true,
min: 1,
max: 5,
},
comment: {
type: String,
default: ""
},
postedBy: {
type: String,
required: true,
index: true
},
reviewOf: {
type: String,
required: true,
index: true
},
postersCreationDate: {
type: Number,
required: true
},
chefsCreationDate: {
type: Number,
required: true
},
chefsId: {
type: String,
required: true
}
});
module.exports.reviewSchema = reviewSchema;
I have another file called recipe.js, where I import reviewSchema and use it as an embedded schema for my Recipe model schema.
const express = require('express');
const mongoose = require('mongoose');
const User = require('../model/user');
require('mongoose-currency').loadType(mongoose);
const Currency = mongoose.Types.Currency;
const Schema = mongoose.Schema;
const reviewSchema = require('../model/review').reviewSchema;
let recipeSchema = new Schema({
name: {
type: String,
required: true
},
description: {
type: String,
},
steps: {
type: String,
required: true,
},
ingredients: {
type: Array,
default: ['1', '2', '3', '4']
},
category: {
type: String,
required: true,
index: true
},
postedBy: {
type: String,
required: true,
},
reviewsOfRecipe: [reviewSchema],
numberOfRatings: {
type: Number,
default: 0
},
totalAddedRatings: {
type: Number,
default: 0
},
reviewAverage: {
type: Number,
default: undefined
},
postersCreationDate: {
type: Number,
index: true
},
likedBy: {
type: Array
},
reviewedBy: {
type: Array
}
});
recipeSchema.methods.updateReviewAverage = function(){
let recipe = this;
this.reviewAverage = this.totalAddedRatings / this.numberOfRatings;
};
let Recipe = mongoose.model('Recipe', recipeSchema);
module.exports = Recipe;
I have another file called recipeRouter.js where I use reviewSchema to construct a review to then later insert it into the embedded reviewsOfRecipes array in my Recipe document. In my recipRouter.js file, every time my code tries to do this....
Recipe.findOne({name: req.params.name}).then((recipe) => {
let review_ = new reviewSchema({
comment: req.body.comment
rating: req.body.score
});
recipe.reviewsOfRecipe.push(review_);
})
...I get this error.
TypeError: reviewSchema is not a constructor
Previously, when I ran into this problem, I had the reviewSchema in the same file as my Recipe model schema. Since then, I split the two into each having their own file. And I made sure to properly export module.exports.reviewSchema = reviewSchema; in my review.js file, and made sure to have const reviewSchema = require('../model/review').reviewSchema; in both my recipe.js and recipeRouter.js files. Yet still this issue still comes up/ I would greatly appreciate it if someone could point out what may be the issue.
You have to export reviewSchema like you did to the other schema (using mongoose.model):
module.exports.reviewSchema = mongoose.model('Review', reviewSchema);

MongoDB Chat Schema

Im trying MongoDB and as a matter of starting point im creating a schema for a chat application that may be simple to scale in the future, so im wondering if this looks correct from what i have been seeing in the docs. So far i have 3 collections User, Room, Message. Also i would need to perform some queries like getting all messages from a sepecific room, get all messages from a specific user, etc
Designed with mongoose:
var user = new mongoose.Schema({
username: { type: String, lowercase: true, unique: true },
email: { type: String, lowercase: true, unique: true },
password: String,
is_active: { type: Boolean, default: false },
});
var room = new mongoose.Schema({
name: { type: String, lowercase: true, unique: true },
topic: String,
users: [user],
messages: [message],
created_at: Date,
updated_at: { type: Date, default: Date.now },
});
var message = new mongoose.Schema({
room: room,
user: user,
message_line: String,
created_at: { type: Date, default: Date.now },
});
var User = mongoose.model('User', user);
var Room = mongoose.model('Room', room);
var Message = mongoose.model('Message', message);
//message model
'use strict';
import mongoose from 'mongoose';
var Schema = mongoose.Schema;
var ObjectId = Schema.Types.ObjectId;
var MessageSchema = new Schema({
send: {
type: ObjectId,
ref: 'User',
required: true
},
message: {
type: String,
required: true
},
date: {
type: Date
},
created_by: {
type: ObjectId,
ref: 'User',
required: true
},
thread: {
type: ObjectId,
ref: 'MsgThread',
required: true
},
is_deleted: [{
type: ObjectId,
ref: 'User'
}]
}, {
timestamps: {
createdAt: 'created_at',
updatedAt: 'last_updated_at'
}
});
export default mongoose.model('Message', MessageSchema);
//dont use rooms,,use thread like groupchat or personalChat
import mongoose from 'mongoose';
var Schema = mongoose.Schema;
var ObjectId = Schema.Types.ObjectId;
const s3 = require("../../utils/s3");
var MsgThreadSchema = new Schema({
users: [{
type: ObjectId,
ref: 'User'
}],
group_name: {
type: String
},
created_by: {
type: ObjectId,
ref: 'User'
},
community: {
type: ObjectId,
ref: 'Community'
},
image_url: {
type: String
}
}, {
timestamps: {
createdAt: 'created_at',
updatedAt: 'last_updated_at'
}
});
export default mongoose.model('MsgThread', MsgThreadSchema);

Categories

Resources