Trying to use mongoose with vue and getting error - javascript

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.

Related

Method does not return whole object

When I call the method buildCommand, it does not return the property message, but I found out that if I remove some properties out of buildCommand, it works.
This is the method I call
const buildCommand = (commandJSON) => {
return new Command({
prefix: commandJSON.prefix,
command: commandJSON.command,
aliases: commandJSON.aliases,
parameters: commandJSON.parameters,
message: commandJSON.message,
response: commandJSON.response,
commandMedium: commandJSON.commandMedium,
enabled: commandJSON.enabled,
isDefault: commandJSON.isDefault,
permission: commandJSON.permission,
cooldown: commandJSON.cooldown,
});
};
This is how I call the method
const newCommand = buildCommand(commandJSON);
commandJSON looks like this
{ prefix: '!', command: 'laugh', message: 'hahaha' }
UPDATE 2
Here is my whole Command Model
const mongoose = require('mongoose');
const commandSchema = mongoose.Schema({
prefix: {
type: String,
default: '!',
},
command: {
type: String,
required: true,
},
aliases: {
type: Array,
},
parameters: {
type: Array,
},
message: {
type: String,
},
response: {
type: String,
enum: ['chat', 'whisper'],
default: 'chat',
},
commandMedium: {
type: String,
enum: ['offline', 'online', 'both'],
default: 'both',
},
enabled: {
type: Boolean,
default: true,
},
isDefault: {
type: Boolean,
default: false,
},
permission: {
type: String,
enum: ['everyone', 'subscriber', 'vip', 'moderator', 'broadcaster'],
default: 'everyone',
},
cooldown: {
globalCooldown:{type:Boolean, default:false},
globalDuration:{type:Number, default:0},
userDuration:{type:Number,default:0},
}
});
module.exports = mongoose.model('Commands', commandSchema, 'TwitchUsers');
Command is just a Mongoose model. There's nothing async in there, you can (and should) remove the async/await stuff.
You can simply do const newCommand = new Command(commandJSON), job done.

Handlebars each statement can access data that handlebars won't access directly

I have a simple help desk app I've been building, where user can make request for site changes. One of the features is being able to see all request made by a specific person, which is working. However on that page I wanted to have something akin to "User's Request" where user is the person's page you are on. However I can't seem to get it to work without some weird issues. If I use:
{{#each request}}
{{user.firstName}}'s Request
{{/each}}
It works but I end up with the header being written as many times as the user has request. However, when I tried:
{{request.user.firstName}}
It returns nothing.
My route is populating user data, so I think I should be able to reference it directly. Here's the route:
// list Request by User
router.get('/user/:userId', (req, res) => {
Request.find({user: req.params.userId})
.populate('user')
.populate('request')
.then(request => {
res.render('request/user', {
request: request,
});
});
});
Here's the schema:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
// Create Schema
const RequestSchema = new Schema({
title: {
type: String,
required: true,
},
body: {
type: String,
required: true,
},
status: {
type: String,
default: 'new',
},
priority: {
type: String,
default: 'low',
},
project: {
type: String,
default: 'miscellaneous',
},
category: {
type: String,
default: 'change',
category: ['change', 'bug', 'enhancement', 'investigation', 'minor_task', 'major_task', 'question'],
},
organization: {
type: String,
default: 'any',
},
assignedUser: {
type: String,
default: 'venkat',
},
allowComments: {
type: Boolean,
default: true,
},
user: {
type: Schema.Types.ObjectId,
ref: 'users',
},
lastUser: {
type: Schema.Types.ObjectId,
ref: 'users',
},
date: {
type: Date,
default: Date.now,
},
lastUpdate: {
type: Date,
default: Date.now,
},
comments: [{
commentBody: {
type: String,
required: true,
},
commentDate: {
type: Date,
default: Date.now,
},
commentUser: {
type: Schema.Types.ObjectId,
ref: 'users',
},
}],
});
// Create collection and add Schema
mongoose.model('request', RequestSchema);
The rest of the code is at: https://github.com/Abourass/avm_req_desk
If anyone is wondering how, the answer was to add the array identifier to the dot path notation:
<h4>{{request.0.user.firstName}}'s Request</h4>

$push replacing values in array instead of adding

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.

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

Manipulating Mongoose/MongoDB Array using Node.js

I've noticed there's little documentation and info about how I should manipulate an array of objects using Mongoosejs.
I have the following model/Schema for an User:
'use strict';
/**
* Module Dependencies
*/
var bcrypt = require('bcrypt-nodejs');
var crypto = require('crypto');
var mongoose = require('mongoose');
/**
* Custom types
*/
var ObjectId = mongoose.Schema.Types.ObjectId;
var userSchema = new mongoose.Schema({
email: { type: String, unique: true, index: true },
password: { type: String },
type: { type: String, default: 'user' },
facebook: { type: String, unique: true, sparse: true },
twitter: { type: String, unique: true, sparse: true },
google: { type: String, unique: true, sparse: true },
github: { type: String, unique: true, sparse: true },
tokens: Array,
profile: {
name: { type: String, default: '' },
gender: { type: String, default: '' },
location: { type: String, default: '' },
website: { type: String, default: '' },
picture: { type: String, default: '' },
phone: {
work: { type: String, default: '' },
home: { type: String, default: '' },
mobile: { type: String, default: '' }
}
},
activity: {
date_established: { type: Date, default: Date.now },
last_logon: { type: Date, default: Date.now },
last_updated: { type: Date }
},
resetPasswordToken: { type: String },
resetPasswordExpires: { type: Date },
verified: { type: Boolean, default: true },
verifyToken: { type: String },
enhancedSecurity: {
enabled: { type: Boolean, default: false },
type: { type: String }, // sms or totp
token: { type: String },
period: { type: Number },
sms: { type: String },
smsExpires: { type: Date }
},
friends: [{
friend: { type: ObjectId, ref: 'User' },
verified: { type: Boolean, default: false }
}]
});
/* (...) some functions that aren't necessary to be shown here */
module.exports = mongoose.model('User', userSchema);
So as you can check I defined Friends inside User like this:
friends: [{
friend: { type: ObjectId, ref: 'User' },
verified: { type: Boolean, default: false }
}]
Now the question is how can I add, edit and delete this array in a Node.js script?
BOTTOMLINE: How can I manipulate arrays that are inside MongoDB Schemas, using Node.js and Mongoose.js? Do I always have to create a Schema function or can I access it directly?
EDIT (13/07/2014): So far I've created a HTTP GET that gives me the array like this:
app.get('/workspace/friends/:userid', passportConf.isAuthenticated, function (req, res) {
User.find({_id: req.params.userid}, function (err, items) {
if (err) {
return (err, null);
}
console.log(items[0].friends);
res.json(items[0].friends);
});
});
But this only returns an array of friendIds, but what if I want to create some sort of '/workspace/friends/:userid/del/:friendid' POST, or add POST. I can't seem to figure out how I can get this done.
You can do something like following
app.get('/workspace/friends/:userid/delete/:friendId', passportConf.isAuthenticated, function (req, res) {
User.findOne({_id: req.params.userid}, function (err, user) {
if (err) {
return (err, null);
}
for (var i = 0; i < user.friends.length; i++) {
if (user.friends[i]._id === req.params.friendId) {
user.friends = user.friends.splice(i,1)
}
}
user.save(function(err, user, numAffected){
if (!err )res.json(user)
res.send('error, couldn\'t save: %s', err)
})
});
});
What it says in mongoose docs is that
"The callback will receive three parameters, err if an error occurred, [model] which is the saved [model], and numberAffected which will be 1 when the document was found and updated in the database, otherwise 0.
The fn callback is optional. If no fn is passed and validation fails, the validation error will be emitted on the connection used to create this model."
If you need to manipulate arrays, you should convert these in objects before.
User.findOne({_id: req.params.userid}, function (err, user) {
if (err) {
return (err, null);
}
var user = user.toObject();
//... your code, an example =>
delete user.friends;
res.json(user);
});
Regards, Nicholls

Categories

Resources