EDIT: This is not a server-side problem. Please read the question carefully.
I am building a solution using Mongoose, Express, Node, and Angular. I am attempting to send my Mongoose schema file client side to be parsed. I have successfully acquired the data in an object in my controller script (client side,) structured like so:
{
href: {type: String},
text: {type: String, trim:true},
dropdown: {type: Boolean},
dropdownList: {type: Array}
}
This is passed through $scope.$apply (because it is being recieved in a callback,) and it is recieved in the HTML like this:
{
href: {},
text: {trim:true},
dropdown: {},
dropdownList: {}
}
Having the data types is extremely important for my implementation. Any thoughts?
If you don't care about monkey patching function object you can do this way.
Add following anywhere before your res.json code run in server or even in client browser.
Function.prototype.toJSON = function() { return this.name; }
Test with node
# node
> var schema = {
... href: {type: String},
... text: {type: String, trim:true},
... dropdown: {type: Boolean},
... dropdownList: {type: Array}
... }
undefined
> schema
{ href: { type: [Function: String] },
text: { type: [Function: String], trim: true },
dropdown: { type: [Function: Boolean] },
dropdownList: { type: [Function: Array] } }
> JSON.stringify(schema)
'{"href":{},"text":{"trim":true},"dropdown":{},"dropdownList":{}}'
> Function.prototype.toJSON = function() { return this.name; }
[Function]
> JSON.stringify(schema)
'{"href":{"type":"String"},"text":{"type":"String","trim":true},"dropdown":{"type":"Boolean"},"dropdownList":{"type":"Array"}}'
>
in your object your trying to assign something like String, Array, Boolean.. and note that those values are not string values these are only keywords. if u have numbers you can do like this, so you need to use those values as string values
{
href: {type: 'String'},
text: {type: 'String', trim:true},
dropdown: {type: 'Boolean'},
dropdownList: {type: 'Array'}
};
here is a demo
Related
I'm building a form management program but right now I'm just trying to build a queue system to handle all the forms when they're assigned to someone.
when I call this first function, it should populate the elements of the activeWork array by pulling from each collection that the entries reference, there are several collections that could be referenced in active work, so I'm trying to use the collection type field to determine what collection to pull from, I don't know if I formatted any of this correctly because its my first time building any of this.
import statesPersons from "./statesPersons.schema.js";
export async function getStatesPersonsActiveWorkByProfileId(req, res){
try{
const { profileId } = req.params
const data = await statesPersons.find({profileId})
.populate('statesPersons.activeWork.referenceId')
return res.send({
message: "success",
data: data,
status: 200 })
}catch(e) {
console.error(e.message)
return res.send({
message: "couldn't fetch active work",
data: null,
status: 500 })
}
}
Here is the schema for statesPersons, the collection where active work is stored.
import mongoose, {model, Schema} from "mongoose";
const activeWorkSchema = new Schema({
active: Boolean,
collectionType: {
type: String,
enum: ['messages'],
},
referenceId: {
type: Schema.Types.ObjectId,
refPath: "statesPersons.activeWork.collectionType"
},
sentBy: {
type: Schema.Types.String,
ref: "statesPerson",
},
sentTo: {
type: Schema.Types.String,
ref: "statesPerson",
},
timeRecived: Date,
dueDate: Date,
subject: String,
viewed: Boolean,
content: {},
})
const statesPersonsSchema = new Schema({
profileId:{
type: String,
required: true,
unique: true
},
department: {
type: String,
required: true,
index: true,
},
firstName: String,
lastName: String,
location: String,
org: String,
title: String,
jobDescription: String,
email: {
type: String,
lowercase: true,
},
phoneNumber: String,
activeWork: [activeWorkSchema],
emailList: [String],
jobAssignments: [String],
affiantInfo: {
affiantInfoTitle: String,
affiantInfoExperience: String,
},
assessments: [
{
assessdBy: {
type: Schema.Types.ObjectId,
ref: "statesPerson",
},
dueDate: Date,
questions: {},
},
],
});
export default mongoose.model("statesPersons", statesPersonsSchema);
When I make a query, I get:
Cannot populate path statesPersons.activeWork.referenceId because it is not in your schema. Set the strictPopulate option to false to override.
I don't know if I formatted my populate correctly or if the problem is in my schema,
I was working on a project where we can create a form like google forms and get responses from users, and then we can view those responses in the admin panel.
My English is not that good I tried my best to explain the problem!
I am using MERN Stack so I was tucked into a problem related to how to save the questions and record the responses in MongoDB in a standard way in objects and arrays.
currently I added this as a form model :
const formSchema = new Schema({
usererId: { type: Schema.Types.ObjectId, ref: 'User' },
title: { type: String, required: true },
description: { type: String},
username: { type: String, required: true },
password: { type: String, required: true },
isEnabled: { type: Boolean, default: true },
expiresOn: { type: Date, default: null },
fields: [
{
title: { type: String, required: true },
placeholder: { type: String, required: false },
type: { type: String, required: true },
required: { type: Boolean, required: true },
options: [
{
title: { type: Object, required: true },
priority: { type: Number, default: 0, required: true }
}
],
priority: { type: Number, required: true, default: 0 },
enabled: { type: Boolean, default: true, required: true }
}
],
}, {
timestamps: true
})
and form responses :
const formResponseSchema = new Schema({
digitalFormId: { type: Schema.Types.ObjectId, ref: 'Form' },
isVerified: { type: Boolean, default: false },
formResponse: [{ type: Object, required: true }],
}, {
timestamps: true
})
I don't know if this approach is good, I myself like it's not like a standard one and I m confused, Someone please tell me how should I do it and what is the perfect way of doing it,
If you have a problem understanding what I am saying just tell me simply how a google form works in the backend from API view, like question ID server-side validation and response submit, that time what type of request is sent to the server, something like this !
If you don't mind please take out some time and write a brief approach of what type of Schema should I use and how should I save them.
Something more important is what approach to use while checking the form response data coming from the client to validate on server-side means on express API, like {questionId: idofquestion, value:'Value of the response of the particular question'}, later checking the question label and all other things with the form questions and all validation rules to fetch from them and check, but I don't know how to do that It's really confusing for me.
Thanks in Advance for the help! ❤️
Good day all,
i'm trying to save image galleries where each image can have up to 5 tags associated with them. So in the Document the Gallery field is an array that has multiple values of which the Tag attribute which itself is an array of Tags.
I'm having issue saving an image where the user adds 2 or more tags for that picture. below this is what i have in my mongoose user schema
gallery : [{
origin : {type: String, trim: true, default: null},
uploadOn: {type: Date, Default: null},
title: { type: String, trim: true, default: null},
caption: { type: String, trim: true, default: null },
tag: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Imagetag', unique: true, sparse: true }],
imageLink: { type: String, trim: true }
}]
and this is my update script
var query = {username:'testUser'};
var options = { runValidators: true };
var toUpdate = {
$addToSet : {
gallery : {
origin : req.body.orgin,
uploadOn: new Date(),
title: req.body.title,
caption: req.body.caption,
tag: '59a5fea0382f1305841f0d86' // working
$addToSet: { tag: { $each: ['59a5fea0382f1305841f0d86', '59a5fea0382f1305841f0d88'] } } , // not working
$push: { tag: { $each: ['59a5fea0382f1305841f0d86', '59a5fea0382f1305841f0d88'] } } , // not working
imageLink: req.body.path
}
}
};
// proceed to update
var user = await User.findOneAndUpdate(query, toUpdate, options);
i have listed the different combination that i have tried without success. i do not want to have to make multiple calls to update the tags one by one for that same image.
This is the model I am working with:
name: {
type: String
},
payment: {
id: {
type: String,
required: true
},
cards: [
{
id: {
type: String
},
is_default: {
type: Boolean,
"default": false
}
}
]
}
I want to add a card to the cards array, for example:
card =
id: "some_token"
is_default: true
I am using the update method to push the card to the array, but it won't add the card to the document. Instead, it creates a new document with only those fields:
{
id: "some_token",
is_default: true,
_id: someId
}
Any idea how I can update the actual document I am targeting instead of creating a new document?
Here's my code (using CoffeeScript):
update_where =
payment:
id: "some_id"
update_push =
$push:
'payment.cards':
id: card_token
is_default: false
Customer.update update_where, update_push, {upsert: true}, (err, results) ->
# Do something with the results
Oh… I just noticed my mistake. The problem was in the where statement.
I was doing:
payment:
id: "some_id"
But the right thing to write is the following:
'payment.id': 'some_id'
And it now works!
Forgive me as I'm pretty new to Mongoose and MEAN in general.
I am curious if an if statement like this would work to prevent a user from pushing themselves into an array twice.
Right now I'm using ng-hide to hide the 'attend' button, but I'd like to learn of a way to prevent it altogether in mongoose.
export function attending(req: express.Request, res: express.Response, next: Function){
if(req.params.id.attending.indexOf(req['payload']._id) !== -1) {
Event.update({_id: req.params.id}, {$push: {'attending': req['payload']._id }, $inc: {numGuests: -1}}, (err)=> {
if (err) return next (err)
User.update({user}, {$push: {'attending': event}}, (err)=> {
if(err) return next (err);
res.json({message: "You're In!"});
})
});
}
}
Here is the model
let eventSchema = new mongoose.Schema({
title: {type: String, required: true},
name:{type: String, required: true},
eventAddress: { type: String, required: true},
dateCreated: {type: Number},
eventCreator: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true },
attending: [{ type: mongoose.Schema.Types.ObjectId, ref: 'User'}]
});
Thanks for any suggestions!