Mongodb and Node js - stack

i am new in node js, and I am trying to build an app quiz engine using node js and mongo DB. I am not sure what I need to make a schema for quiz engine. So anyone can help me.

Here is an example of a User Schema...
var userSchema = new Schema({
name: {
type: String,
unique: true,
required: true
},
password: {
type: String,
required: true
}
});
But like the comment stated, you will have to be more specific.

As far as i can guess, a quiz will be given by user and it will have questions. So, you can make two entities :
i) User entity
ii) Quiz/Questions entity
User entity schema :
module.exports = {
attributes = {
name: {
type: String,
required: true
},
password: {
type: String,
required: true
}
password: {
type: String,
required: true
}
}
};
Question entity schema :
module.exports = {
attributes = {
questionLabel: {
type: 'String',
required: true
},
choices: {
type: 'Array',
required: true
}
};

Hello this is my schema
enter code here var mongoose = require("mongoose");
var Schema = mongoose.Schema;
var img_schema = new Schema({
title:{type:String,require:true},
creator:{type:Schema.Types.ObjectId, ref: "User" },
extension:{type:String,require:true},
foto:{type:String,require:true},
uso:{type:String,require:true}
});
var Imagen = mongoose.model("Imagen",img_schema);
module.exports = Imagen;

This is the example of user schema. you can replace with your requirement.
// User Schema
var UserSchema = mongoose.Schema({
username: {
type: String,
index: true
},
password: {
type: String
},
email: {
type: String
},
name: {
type: String
},
profileimage:{
type: String
}
});
var User = module.exports = mongoose.model('User', UserSchema);

I will suggest you to use mongoose to define your mongoDB collection schemas. Mongoose facilitates a lot of processes between nodejs and mongoDB.
You can install mongoose using following command:
npm i mongoose
Then create a schema like this:
import mongoose from 'mongoose';
const { Schema } = mongoose; //Pulling schema out of mongoose object
const QuizEngineSchema = new Schema({
name: String,
phoneNumber: Number,
// other data that you need to save in your model
},
{timestamps: true},
{id: false});
//Plugging the Schema into the model
const QuizEngine = mongoose.Model('QuizEngine',QuizEngineSchema);
export default QuizEngine;
Hope this helps!

Related

Return ONLY selected fields within a TypeORM find request

I'm struggling in returning only selected fields in my TypeORM find request.
Assuming the following request
const data = await AppDataSource.manager.find(User, {
select: {
id: true,
hash: true,
firstname: true,
lastname: false,
},
take: 10, // Just here to shrink dataset
});
The script works pretty well excepted that it return every field of my model, with default value initialized.
[
User {
prefix: 'usr',
hash: 'usr_835b0ad2-XXXXXX',
email: undefined,
accountValidated: false,
role: 'free',
myKeyOne: true,
myKeyTwo: false,
gender: 'unspecified',
lastConnexion: 2023-01-19T10:11:02.733Z,
pendingDeletion: false,
deletionDate: undefined,
firstname: 'Clément',
lastname: undefined,
password: undefined,
facebookId: undefined,
googleId: undefined,
id: 158
},
...
]
Of course, it's not usable as it, because I have extensive relations, and thus the payload would be extremely heavy.
Are you aware of a method / a way to remove all unnecessary fields ?
i.e. I'm expecting
[
User {
id: 124,
hash: 'urs_XXXX',
firstname: 'Clément',
},
...
]
In older versions of typeorm I think you need to select with an array of strings, try:
select: ["id", "hash", "firstname"],
See this older version of the docs: https://github.com/typeorm/typeorm/blob/bc60dd559ba42af083ddea17f01205c78c83c7e0/docs/find-options.md
After hours of researches I've finally found out why it behaved like this.
TypeORM relies on class definitions and typescript so...
if you have typescript default values OR if you have rewrite your constructor, all the "default" properties are injected.
Assuming a User model
❌ You should not do
#Entity({ name: 'users' })
class User {
#Column()
firstname?: string;
#Column({ nullable: true })
lastname?: string;
#Column({ unique: true, nullable: false })
email!: string;
#Column({ name: 'account_validated', nullable: false})
accountValidated?: boolean = false
//Your other fields...
}
✅ You should do
#Entity({ name: 'users' })
class User {
#Column()
firstname?: string;
#Column({ nullable: true })
lastname?: string;
#Column({ unique: true, nullable: false })
email!: string;
// Use default argument of the decorator
#Column({ name: 'account_validated', nullable: false, default: false})
accountValidated?: boolean
//Your other fields...
}
And if you need in some way to init a default, then create a public static method which return the Entity instead of using the constructor.
#Entity({ name: 'users' })
class User {
//...fields
public static init(...params): User {
let _user = new User()
//...populate your object
return _user
}
}

How do I use entity listeners in TypeORM without using decorators?

I'm working on creating a users table. I want to be able to set the password field (which should ideally not be a saved field (not sure if typeorm allows that yet)) and on insert/update I want to look and see if the password field is set, if it is I want to save a new salt and a hashed password to the database instead. I found some thing that showed me how to do it with the #BeforeInsert entity listener, but i'm using javascript without decorators.
user.entity.js:
module.exports = new EntitySchema({
name: "User",
columns: {
id: { primary: true, type: "uuid", generated: "uuid" },
username: { type: "text", unique: true },
password: { type: "text"}, //i'd prefer this to be hashed_password and password to only be used in the listeners
salt: { type: "text" },
email: { type: "text", unique: true },
},
})

Jaydata web api with OData provider -- provider fallback failed error

I'm developing an application with jaydata, OData and web api. Source code is given below:
$(document).ready(function () {
$data.Entity.extend('$org.types.Student', {
Name: { type: 'Edm.String', nullable: false, required: true, maxLength: 40 },
Id: { key: true, type: 'Edm.Int32', nullable: false, computed: false, required: true },
Gender: { type: 'Edm.String', nullable: false, required: true, maxLength: 40 },
Age: { type: 'Edm.Int32', nullable: false, required: true, maxLength: 40 }
});
$data.EntityContext.extend("$org.types.OrgContext", {
Students: { type: $data.EntitySet, elementType: $org.types.Student },
});
var context = new $org.types.OrgContext({ name: 'OData', oDataServiceHost: '/api/students' });
context.onReady(function () {
console.log('context initialized.');
});
});
In above JavaScript code, I defined an entity named Student. In context.onReady() method, I'm getting the following error:
Provider fallback failed! jaydata.min.js:100
Any idea, how I could get rid of this error??
As per suggested solution, I tried to change the key from required to computed. But sadly its still giving the same error. Modified code is given below.
$(document).ready(function () {
$data.Entity.extend('Student', {
Id: { key: true, type: 'int', computed: true },
Name: { type: 'string', required: true}
});
$data.EntityContext.extend("$org.types.OrgContext", {
Students: { type: $data.EntitySet, elementType: Student },
});
var context = new $org.types.OrgContext({
name: 'OData',
oDataServiceHost: '/api/students'
});
context.onReady(function () {
console.log('context initialized.');
});
});
I thinks the issue is with Odata provider because I tried the same code with indexdb provider and its working properly.
The issue is caused by the value oDataServiceHost parameter. You should configure it with the service host, not with a particular collection of the service. I don't know if the provider name is case-sensitive or not, but 'oData' is 100% sure.
For WebAPI + OData endpoints the configuration should look like this:
var context = new $org.types.OrgContext({
name: 'oData',
oDataServiceHost: '/odata'
});

Extjs4 grid load using URL working with localhost but not with Ip address

My application grid is loading data using the webservice URL to fill grid with coming data. When Im giving URL like
function gridSectionResources()
{
Ext.define('Person', {
extend: 'Ext.data.Model',
fields: ['EmployeeID', 'FirstName', 'LastName','Designation','Role','BillingRate','SignedOn','SignedOff']
});
var store = Ext.create('Ext.data.Store', {
autoLoad: true,
//autoSync: true,
model: 'Person',
proxy: {
type: 'rest',
url:'http://localhost:2012/HBWebService/ws/employees',
// url:'js/Manager/data.json',
reader: {
type: 'json',
root: 'Project'
},
writer: {
type: 'json'
}
}
});
Working fine but
If I'm giving url:'http://172.166.11.9:2012/HBWebService/ws/employees'. It is not working
You must use JsonP proxy for getting data from another domain.
http://docs.sencha.com/ext-js/4-0/#!/api/Ext.data.proxy.JsonP
Ext.define('Person', {
extend: 'Ext.data.Model',
fields: ['EmployeeID', 'FirstName', 'LastName','Designation','Role','BillingRate','SignedOn','SignedOff']
});
var store = Ext.create('Ext.data.Store', {
autoLoad: true,
//autoSync: true,
model: 'Person',
proxy: {
type: 'jsonp',
url:'http://localhost:2012/HBWebService/ws/employees',
// url:'js/Manager/data.json',
reader: {
type: 'json',
root: 'Project'
},
writer: {
type: 'json'
}
}
});

embedForm saving problem - Symfony

I have schema like:
Schema:
article:
id: ~
title: { type: VARCHAR, size: '255', required: true }
created_at: { type: TIMESTAMP, required: true }
updated_at: { type: TIMESTAMP, required: true }
article_data:
id: ~
article_data: { type: BLOB, required: true }
article_filename: { type: VARCHAR, size: '255'}
article_id: { type: INTEGER, required: true, foreignTable: article, foreignReference: id, onDelete: cascade }
So, in my article admin module, I'd like to display the article_data widget, which is a file upload.
Everything is fine. But when saving the uploaded file to the server, the article_id field is null.
Is there a way i could get the id of the article and save it as the article_id of the article_data table?
Thanks
EDIT:
I think I need to override the saveEmbeddedForm() method, but I am not sure what I'd need to do.
Could someone help with some code for a saveEmbeddedForm()?
Thanks
I don't known Propel, but in Doctrine you could do something like this:
class ArticleForm extends BaseForm
{
public function configure()
{
parent::configure();
$form = new sfForm();
$datas = $this->getObject()->getDatas();
foreach ($datas as $index => $data)
$form->embedForm($index, new ArticleDataForm($data));
$this->embedForm('dataForms', $form);
}
public function saveEmbeddedForm($con = null, $forms = null)
{
$dataForms = $this->getEmbeddedForm('dataForms')->getEmbeddedForms();
foreach ($dataForms as $dataForm)
$dataForm->getObject()->setArticle($this->getObject());
parent::saveEmbeddedForm($con, $forms);
}
}

Resources