Trying to reference one collection in mongo via another model's virtual. Currently the only output I'm getting is 'undefined'. Was able to execute this in my main js file as a standalone query but can't figure out how to get this to function as a virtual. Help appreciated.
const mongoose = require('mongoose');
const { stylesList } = require('../styles.js')
const Schema = mongoose.Schema;
const Post = require('./post')
const options = { toJSON: { virtuals: true } };
// options object for the schema, passed in after the actual schema.
const BrandSchema = new Schema({
name: {
type: String,
unique: true,
required: true
},
linkedBrands: [String],
styles: [{ type: String, enum: stylesList }],
links: {
homepage: {
type: String,
required: true
},
grailed: {
type: String,
required: true
},
wikipedia: String
},
bannerImage: String,
likes: {
type: Number,
default: 0
}
}, options);
BrandSchema.set('toObject', { getters: true });
BrandSchema.virtual('amountWorn').get(async function() {
const wornPosts = await Post.find({includedBrands: this._id});
return wornPosts.length
});
module.exports = mongoose.model('Brand', BrandSchema)
Related
I was trying from some object get others info from it. Like from object A, get the objectId from object B, and printing the object B instead the object A. But I got this error message:
TypeError: Cannot read properties of null (reading 'idTechnical')
I'm using nodejs
My function:
const getFinalReport = async (req, res) => {
try{
const finalReport = await Final.findById(req.params.id);
const technicalReport = await Technical.findById(finalReport.idTechnical);
const finantialReport = await Finantial.findById(finalReport.idFinantial);
const writeReport = await Write.findById(finalReport.idWrite);
res.status(200).json(finalReport, {technicalReport, finantialReport, writeReport});
}catch(err){
console.error(err);
res.status(500).send({"msg": "Internal Error!"})
}}
My model:
const finalreportSchema = new mongoose.Schema({
idWrite: { type: mongoose.Schema.Types.ObjectId, ref: "reports", default:''},
idTechnical: { type: mongoose.Schema.Types.ObjectId, ref: "technincal", default: ''},
idFinantial: { type: mongoose.Schema.Types.ObjectId, ref: "finantial", default:''},
isConclude: { type: Boolean, default: false }
},
{
timestamps:true
});
const Report = mongoose.model('final-report', finalreportSchema);
module.exports = Report;
My techincal model:
const mongoose = require("mongoose");
const TechincalSchema = mongoose.Schema({
idInstallationNumber: { type: mongoose.Schema.Types.ObjectId, ref: "installations" },
months: { type: String, required: true },
previousBalance: { type: String, required: true },
actualBalance: { type: String, required: true },
injected: { type: String, required: true },
totalInjected: { type: String, required: true },
},
{
timestamps:true
});
const Technical = mongoose.model('technincal', TechincalSchema);
module.exports = Technical;
Same happen on the Finantial and Write Reports. Had someone had some clue?
Sorry for my english but, this is the first time asking, and also it's been a while that I write something in english (isn't my first language)
I want to store or push whole reference document not a single reference id in Mongoose using Node.js.
Here user api details schema:
const {Schema} = require("mongoose");
const mongoose = require("mongoose");
const apiDetailSchema = new Schema({
endpoint:
{
type: String,
required: true,
trim: true
},
method:
{
type: String,
required: true,
trim: true,
},
secret:
{
type: String,
required: true,
trim: true
},
timeout:
{
type: Number,
required: true,
},
microservice:
{
type: String,
required: true,
},
status:
{
type: Number,
required: true,
},
user_type_id:
{
type: Schema.Types.ObjectId,
ref: 'UserType',
required: true
}
});
module.exports = apiDetailSchema;
Permissoin Schema
const {Schema} = require("mongoose");
const mongoose = require("mongoose");
const permission = new Schema({
role:
{
type: Schema.Types.ObjectId,
ref: 'Role'
},
Here I want to store whole api details document not single id
api_details:
[
{
type: Schema.Types.ObjectId,
ref: 'ApiDetail'
}
],
group:
{
type: String,
default: 0,
trim: true
},
status:
{
type: Number,
default: 0,
trim: true
}
});
module.exports = permission;
And here I push the ids like this:
async createPermission(req, res)
{
const permission = new Permission({
"role": req.body.role,
"group": req.body.group,
"status": req.body.status
});
const newPermissoin = await permission.save();
if(newPermissoin) {
const updatePermission = await Permission.findByIdAndUpdate(
newPermissoin._id,
{ $push: { "api_details": req.body.api_details_id } },
{ new: true, useFindAndModify: false }
);
return res.json( Response.success({message:
"Permission created successfully!", data: updatePermission}) );
}
}
How do I store the whole documents of api details in array form but here only reference of ids are stored.
I am working on a MERN stack project where A user can perform CRUD operations on Goals. I use mongoose for object modeling. I want to create a virtual field named stepAvg to find out some information about each goal by using the step model.
Relationship information
Each user has many goals.
Each goal has many steps.
GoalModel.js
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const StepModel = require("./StepModel");
const GoalSchema = new Schema({
category: { type: Schema.ObjectId, ref: "Category", required: true },
title: { type: String, required: true },
startDate: { type: Date, required: true },
completionDate: { type: Date, required: true },
commitment: { type: String, required: true },
obstacle: { type: String, default: null },
celebration: { type: String, default: null },
user: { type: Schema.ObjectId, ref: "User", required: true },
steps: [{ type: Schema.Types.ObjectId, ref: "Step"}],
}, {
toJSON: { virtuals: true },
toObject: { virtuals: true }
}, {timestamps: true});
GoalSchema.virtual('stepAvg').get(async function() {
let steps = await StepModel.find({ goal: this.id });
// if I console steps it return the data correctly.
let totalSteps = steps.length;
if (totalSteps) {
let completedSteps = steps.filter(function(step) {
return step.isCompleted;
}).length;
let avg = ( completedSteps / totalSteps) * 100;
return avg;
}
return 0;
});
module.exports = mongoose.model("Goal", GoalSchema);
As you can see I create a virtual field stepAvg but every time it gives me the empty object. It actually returns the promise.
Postman screenshot
The error started after I started using the discriminator.
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const Base = require("../config/Base");
const Refill = Base.discriminator(
"Refill",
new Schema({
cylinderSize: { type: Number, required: true },
cylinderSwap: { type: Boolean, required: true },
quantity: { type: Number, required: true },
location: {
type: { type: String },
coordinates: [Number]
}
})
);
Refill.index({ location: "2dsphere" });
module.exports = mongoose.model("Refill");
This returns the error Refill.index is not a function
In Mongoose, indexes must be created on schemas, not models. In your case, the Refill object is a model. One approach is to implement this in three steps:
Create the schema
Add the index to the schema
Create the model
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const Base = require("../config/Base");
const refillSchema =
new Schema({
cylinderSize: { type: Number, required: true },
cylinderSwap: { type: Boolean, required: true },
quantity: { type: Number, required: true },
location: {
type: { type: String },
coordinates: [Number]
}
});
refillSchema.index({ location: "2dsphere" });
const Refill = Base.discriminator("Refill", refillSchema);
module.exports = mongoose.model("Refill");
I just took out the Refill.index({ location: "2dsphere" }); and the rest of my code is working fine apparently indexing that field wasn't necessary.
I have data like ug.tutionfees andpg.tutionfees in MongoDB. How to implement this data in NodeJS model class and angular plz tell me.
My model class:
const mongoose = require('mongoose');
const UniversitySchema = mongoose.Schema({
worldranking:String,
countryranking:String,
universityname:String,
bachelorprogram:String,
masterprogram:String,
phdprogram:String,
country:String
},{collection:'us'});
const University =module.exports = mongoose.model('University',UniversitySchema);
I want to implement ug.tutionfees and pg.tutionfees in this model class.
If you have only these ug.tutionfees and pg.tutionfees are two different objects you can add into schema as below:
ug :{
tutionfees :{
type: String
}
},
pg :{
tutionfees :{
type: String
}
}
Check one of my schema structure:
'use strict'
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var rbpiSchema = new Schema({
rbpiId: {
type: String,
required: true,
unique: true
},
name: {
type: String,
required: true
},
description: {
type: String
},
last_action: {
activity: {
type: String
},
status: {
type: String
},
ut: {
type: Number
},
description: {
type: String
}
},
ct: {
type: Number,
require: true,
default: new Date().getTime()
},
ut: {
type: Number,
require: true,
default: new Date().getTime()
}
});
module.exports = mongoose.model('rbpi', rbpiSchema);