Node mongodb stores data as string instead of an object - javascript

I have two same functions, first saves some stuff and also saves ref to productId and second saves another stuff and saves ref to productId too. The problem is first writes ref to poductId as object and everything is ok but second function saves ref as string and in mongodb i see ObjectId but when im trying to display data on screen i cant access into object i have only string with ID of refer. Any ideas?
first model which is ok
const mongoose = require('mongoose')
const dishPositionsSchema = mongoose.Schema({
productId: {
type: mongoose.Schema.Types.ObjectId,
required: true,
ref: 'Products'
},
dishId: {
type: mongoose.Schema.Types.ObjectId,
required: true,
ref: 'Dishes'
},
weight: {
type: Number,
required: true
}
})
module.exports = mongoose.model('DishPositions', dishPositionsSchema)
and second which stores only strings instead of objects
const mongoose = require('mongoose')
const diaryPositionsSchema = mongoose.Schema({
productId: {
type: mongoose.Schema.Types.ObjectId,
required: true,
ref: 'Products'
},
dishId: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Dishes'
},
weight: {
type: Number,
required: true,
required: true
},
timeOfEatingId: {
type: mongoose.Schema.Types.ObjectId,
required: true,
ref: 'TimeOfEating'
},
date: {
type: String,
required: true
}
})
module.exports = mongoose.model('DiaryPositions', diaryPositionsSchema)

I know where i did mistake... i didnt write populate('productId')... everything is fine now thanks!

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.

can a mongoose schema field reference more than one other models

I have a mongoose schema field called "bookmarks" and I would like it to reference more than one model. for example, if I have 2 other models named "post" and "complain". I would like the user to be able to bookmark both of them.
const userSchema = new mongoose.Schema({
fullname: {
type: String,
required: true,
trim: true,
lowercase: true
},
username: {
type: String,
unique: true,
required: true,
trim: true,
lowercase: true
},
email: {
type: String,
unique: true,
required: true,
trim: true,
lowercase: true,
validate(value) {
if (!validator.isEmail(value)) {
throw new Error('Email is invalid')
}
}
},
bookmarks: [{
type: mongoose.Schema.Types.ObjectId,
required: false,
ref: 'Post'
}],
})
below is a post model, where users can post things in general
const postSchema = new mongoose.Schema({
body: {
type: String,
required: true,
trim: true,
lowercase: true
}
})
below is a complain model, where users can post a complain
const complainSchema = new mongoose.Schema({
body: {
type: String,
required: true,
trim: true,
lowercase: true
}
})
How can I get the bookmarks field in the user model to be able to get the object id of both the complain model and the post model?
You can nest those two models in userSchema itself just like you are doing with bookmark schema .
You can also refer to this link , i hope it will resolve your query.
Link - : What is the proper pattern for nested schemas in Mongoose/MongoDB?
Here is the correct way to achieve this.
First remove bookmarks
Add this
ref: {
kind: String, // <-- Model Name post,complain
item: {
type: mongoose.Schema.Types.ObjectId,
refPath: 'ref.kind',
fields: String,
},
},
When you want to fetch the records,you can use populate
model.User.find({})
.populate({ path: 'ref.item' })
.then(data=>{console.log(data)})
.catch(err => {console.log(err)});

Updating count of individual sub document that's in an array of a mongo document

So the example right now is for the User table.. I have a UserWeapon document embedded that is an array of all the weapon's a user has and how many kills they have with the weapon. I want to write a query that when given the userId, weaponId, and new kills, it'll update the sub document accordingly.
So something like
const user = await User.findById(userId);
const userWeapon = await user.userWeapon.findById(weaponId);
userWeapon.kills = userWeapon.kills + newAmmountOfKills
user.save();
What would be the most efficient way to do this?
Schemas:
const UserWeaponSchema = new Schema({
weapon: { type: Schema.Types.ObjectId, ref: 'Weapon' },
user: { type: Schema.Types.ObjectId, ref: 'User' },
kills: {
type: Number,
required: true,
unique: false,
},
deaths: {
type: Number,
required: true,
unique: false
},
equippedSkin: {
type: Schema.Types.ObjectId, ref: 'WeaponSkin',
required: false,
},
ownedWeaponSkins: [{ type: Schema.Types.ObjectId, ref: 'WeaponSkin'}]
});
const UserSchema = new Schema({
username: {
type: String,
required: true,
unique: true,
},
password: {
type: String,
required: true,
},
weapons: [{
type: Schema.Types.ObjectId, ref: 'UserWeapon'
}],
});
You can use $inc operator and run update operation, something like:
UserWeaponSchema.update({ weapon: weaponId, user: userId }, { '$inc': { 'kills': newAmmountOfKills } })

Mongoose schema update is not pick it up by Mongodb database

I've my db already created where I have the following schema:
const ProjectSchema = new mongoose.Schema({
name: { type: String },
description: { type: String },
client: {
type: mongoose.Schema.Types.ObjectId,
ref: 'client'
},
group: {
type: mongoose.Schema.Types.ObjectId,
ref: 'project_group'
}
});
I need to change the schema to
const ProjectSchema = new mongoose.Schema({
name: { type: String, unique: true, required: true },
description: { type: String },
client: {
type: mongoose.Schema.Types.ObjectId,
ref: 'client'
},
group: {
type: mongoose.Schema.Types.ObjectId,
ref: 'project_group'
}
});
because we need to force name to be unique and not null. After change this definition, I see that the db still saving documents with the same name value. My question is, how can I apply any change I've done in my schema? and, how can I do that automatically without doing this manually?
Regards
You most likely need to index that field so it can be quickly searched. Then also restart your server, if you haven't already. It's easy to do if you have MongoDB Compass (the official MongoDB GUI), or you can read this doc.
https://docs.mongodb.com/manual/core/index-single/#create-an-index-on-an-embedded-field

Categories

Resources