$push replacing values in array instead of adding - javascript

I am a begginer using nodeJs, mongoose and MongoDB and i ran into a problem that after several hours of research i cannot solve. I'll try to explain clearly.
First things first, so i'll briefly explain the logic. I have Users that can have several Items, so in each user i want to have an array of objectId's that identify the items they have.
I have User.js and userService.js files, as well as Item.js and itemService.js files.
My User.js file is as follows:
const restful = require('node-restful')
const mongoose = restful.mongoose
const validator = require('validator')
var Schema = mongoose.Schema
const utilizadorSchema = new mongoose.Schema({
username: { type: String, default: '', required: true, unique: true},
email: { type: String, default: '', required: true, unique: true, validate: [validator.isEmail, 'Invalid email']},
password: { type: String, default: '', required: true},
equipaID: [{
type: Schema.Types.ObjectId, ref: 'Equipa'}],
itens: [{
type: Schema.Types.ObjectId, ref: 'Item'}],
poderDeAtaque: { type: Number, default: 10},
poderDeDefesa: { type: Number, default: 10},
healthPoints: { type: Number, default: 100},
classificacaoDuelos: { type: Number, default: 0},
vitorias: { type: Number, default: 0},
derrotas: { type: Number, default: 0},
validado: { type: Boolean, default: false}
})
module.exports = restful.model('Utilizador', utilizadorSchema, 'Utilizadores')
Now, my userService.js file:
const Utilizador = require('./utilizador')
var item = require('./item')
Utilizador.methods(['get', 'post', 'put', 'delete'])
Utilizador.update(
{_id: Utilizador._id},
{ $push: {itens: item._id}},
{ upsert: true}
)
module.exports = Utilizador
Item.js:
const restful = require('node-restful')
const mongoose = restful.mongoose
const itemSchema = new mongoose.Schema({
descricao: { type: String, required: true},
categoria: { type: String, required: true},
nivel: { type: Number, required: true},
poderDeAtaque: { type: Number, required: true},
poderDeDefesa: { type: Number, required: true},
healthPoints: { type: Number, required: true},
})
module.exports = restful.model('Item', itemSchema, 'Itens')
ItemService.js:
const Item = require('./item')
Item.methods(['get', 'post', 'put', 'delete'])
Item.updateOptions({new: true, runValidators: true})
module.exports = Item
So, my problem is this, i can successfully add an item to an user, however, when i try to add another item to the same user, it replaces the value in the array, instead of adding a new one. I've tried using $addToSet instead of $push, but to no success.

Related

Trying to use mongoose with vue and getting error

any time i try to import this the page throws the error of
Uncaught TypeError: Cannot read properties of undefined (reading 'split')
import { User } from '#/assets/schemas'
export default {
name: 'HomeView',
mounted() {
//const user = User.findOne({ id: '1002401206750150836' })
console.log('user')
}
}
when i comment out the import it works but when i add the import back i get that error this is the code for the Schemas.js
const mongoose = require('mongoose');
const User = new mongoose.Schema({
id: { type: String, unique: true, required: true},
bank: { type: Number, default: 2000 },
wallet: { type: Number, default: 0},
chips: { type: Number, default: 0},
level: { type: Number, default: 1},
totalxp: { type: Number, default: 0},
xp: { type: Number, default: 0},
favcolor: { type: String, default: "White"},
cooldowns: {
daily: { type: Date },
monthly: { type: Date },
buychips: { type: Date },
}
})
const Guild = new mongoose.Schema({
id: { type: String, unique: true, required: true},
welcome_channel_id: { type: String, default: null },
new_member_role_id: { type: String, default: null }
})
module.exports = { User: mongoose.model("User", User), Guild: mongoose.model("Guild", Guild) }
Mongoose is not a frontend library, it can not be used with Vue. It relies on Node.js functionality which doesn't exist in the browser. Mongoose is only meant to be used on a backend Node.js server.

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.

How add children(ref) to mongoose?

My lines are empty.
My scheme:
// models/Tobacco.js
const mongoose = require('mongoose');
// FYI: important for populate work!!!
const tobaccoLineSchema = mongoose.Schema({
name: {type: String, required: true},
subTitle: {type: String, required: true},
count: {type: Number, required: true}
});
const Schema = mongoose.Schema;
const TobaccoSchema = new mongoose.Schema({
createdAt: {
type: Date,
default: Date.now
},
title: {
type: String,
required: true
},
subTitle: {
type: String,
required: false
},
bannerSrc: {
type: String,
required: false
},
socials: [],
lines: [
{
type: Schema.Types.ObjectId,
ref: 'tobaccoLine'
}
]
}
,{toObject:{virtuals:true}, toJSON:{virtuals:true}});
const TobaccoLine = mongoose.model('tobaccoLine', tobaccoLineSchema);
module.exports = mongoose.model('tobacco', TobaccoSchema);
Added populate line in API
router.get('/:id', (req, res) => {
Tobacco.findById(req.params.id).populate('lines')
.then(tobacco => res.json(tobacco))
.catch(err => res.status(404).json({ notobaccofound: 'No Tobacco found' }));
});
Database:
How I can't see issues. Client side fetches tobaccos but lines are empty.
Need to add back property into the child entity scheme.
const tobaccoLineSchema = mongoose.Schema({
name: {type: String, required: true},
subTitle: {type: String, required: true},
count: {type: Number, required: true},
_tobacco: { type: Schema.Types.ObjectId,
ref: 'tobacco' }
});

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 } })

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);

Categories

Resources