I am making a webiste using MERN stack, I've managed to insert data from forms in react front end to mongodb but when I made a new form I get a cast to array failed error. I've tried casting to another array in my mongroose model and that worked just fine. the system is a mock online bank, never to be used in any production enviournment
My model:
const mongoose = require('mongoose');
const bcrypt = require('bcrypt');
const Schema = mongoose.Schema;
// Creates the needed schema
let userSchema = new Schema({
name: String,
created_at: Date,
updated_at: Date,
balance: Number,
address: String,
ssn: Number,
bankNumber: Number,
cards: [
{
type: String, // Visa eller Mastercard
cardNumber: Number,
cvc: Number,
expirationDate: Number,
pin: Number,
status: Boolean,
dailyLimit: '9900'
}
],
whitdrawal: [
{
amount: Number,
date: Date, // Skriv auto date logikk
reason: String
}
]
});
// Inserts
userSchema.pre('save', function(next) {
const currentDate = new Date();
this.updated_at = currentDate;
this.date = currentDate;
if (!this.created_at) this.created_at = currentDate;
next();
});
// Creates model for schema
const AtmUser = mongoose.model('AtmUser', userSchema);
// Export so it is available for the rest of the application
module.exports = AtmUser;
Express method for saving this data, data is sent from front end and visible in terminal error message
app.post('/api/newUser', function(req) {
const newUser = AtmUser({
name: req.body.name,
balance: req.body.balance,
address: req.body.address,
ssn: req.body.ssn,
bankNumber: req.body.bankNumber,
cards: [
{
type: req.body.type, // Visa eller Mastercard
cardNumber: req.body.cardNumber,
cvc: req.body.cvc,
expirationDate: req.body.expirationDate,
pin: req.body.pin,
}
],
});
newUser.save(function(err) {
if(err) throw err;
console.log('A new user has been made')
})
})
When trying to cast to whitdrawal arary instead of cards array everything works as expected, part of the erorr message I get in terminal
events.js:167
[0] throw er; // Unhandled 'error' event
[0] ^
[0] ValidationError: AtmUser validation failed: cards: Cast to Array failed for value "[ { type: '234234234' } ]" at path "cards"
[0] at new ValidationError (/Users/andreas/Documents/prosjekt/atm/node_modules/mongoose/lib/error/validation.js:30:11)
I've been trying to spot the error for a few hours but just cannot find it, thank you for all replies! I'd be happy to post more of the code or the entire error message if that would help
After much trial and error I found the answer, it turns out that type is a reserved word, changing it to formType og Type solved the issue in my model.
Corrected model:
app.post('/api/newUser', function(req) {
const newUser = AtmUser({
name: req.body.name,
balance: req.body.balance,
address: req.body.address,
ssn: req.body.ssn,
bankNumber: req.body.bankNumber,
cards: [
{
formType: req.body.type, // Visa eller Mastercard
cardNumber: req.body.cardNumber,
cvc: req.body.cvc,
expirationDate: req.body.expirationDate,
pin: req.body.pin,
}
],
});
newUser.save(function(err) {
if(err) throw err;
console.log('A new user has been made')
})
})
Related
I have the Cast to error in JSON response when Adding the Product Details in the & when adding category showing Error.
const mongoose = require("mongoose");
const { ObjectId } = mongoose.Schema;
{
category: {
type: ObjectId,
ref: "Category",
},
};
Except category Every detail is adding in the mongodb table
You should try mongoose.SchemaTypes.ObjectId
#Prop({ type: mongoose.SchemaTypes.ObjectId, ref: 'ExercisePlan' })
category: string;
And if you are trying to aggregate with _id so you should try
$match: {
category: new Types.ObjectId(inputId),
},
I am trying to return a nested Object that I declared in my mongoose model as follows:
const MessageSchema = new Schema({
messageLog: [
{
transcript: {
type: String
},
recipient: {
type: Schema.Types.ObjectId,
ref: 'User',
required: true
},
sender: {
type: Schema.Types.ObjectId,
ref: 'User',
required: true
}
}]
});
however I am not able to get the value for the inner object back when I try to query for it via a graphql resolver (transcript, sender, recipient are null on gql playground, but updated in db) I have set it up as follows:
query = args.messageId ? { _id: args.messageId } : { _id: new ObjectId() };
const message = await Message.findOneAndUpdate(query, {$addToSet: {messageLog: {transcript: args.messageBody, sender: args.senderId, recipient: args.recipientId}}}, {$setOnInsert: args, upsert: true, new: true, runValidators: true})
return message.messageLog;
I am able to create the new object and the nested messageLog in the db but I can only return the id for some reason as opposed to the the messageLog array of objects. Usually the issue lies in how I am resolving (resolvers) but I am going to put my typeDef here as well in case the issue lies there.
type Message {
_id: ID
transcript: [String]
recipient: [User]
sender: [User]
}
So the solution in case anyone has a similar schema setup and issue is to reference the the typeDefs with the nested levels as well. So since transcript, recipient and sender were nested a level down, the typeDef would have to be defined for the nested object and then referenced on the message type as follows:
type messageLog {
_id: ID
transcript: String
recipient: User
sender: User
}
type Message {
_id: ID
messageLog: [messageLog]
}
and to use populate for the User since it was a schema referenced by the objectId
I'm trying to nest schemas using mongoose, but i got stuck and i don't really know why. Here is what i got.
My parent schema
const Comment = require("./Comment");
const BookSchema = new Schema({
_id: Number,
comments: [{ comment: Comment }],
ratings: [{ rate: Number }],
calculatedRating: Number
});
module.exports = Book = mongoose.model("book", BookSchema);
and child schema
const CommentSchema = new Schema(
{
userName: String,
rating: Number,
body: String,
submit_date: {
type: Date,
default: Date.now
}
},
{ _id: false }
);
module.exports = Comment = mongoose.model("comment", CommentSchema);
And with this setup im getting an error :
"TypeError: Invalid schema configuration: Model is not a valid type
at path comment."
I'm considering that i did something wrong with those exports but I'm not sure.
Your ./Comment should be:
const CommentSchema = new Schema(
{
userName: String,
rating: Number,
body: String,
submit_date: {
type: Date,
default: Date.now
}
},
{ _id: false }
);
module.exports = CommentSchema;
If you define as a new model as you did then it will create it's own collection and will be a new model instead of a sub document schema.
This question already has answers here:
Why does a GraphQL query return null?
(6 answers)
Closed 3 years ago.
Trying to make my first graphQL server, here's what I have written so far.
https://gist.github.com/tharakabimal/7f2947e805e69f67af2b633268db0406
Following error pops up on GraphQL when I try to filter the users by username.
Error on GraphQL
The error occurs in the users field in UserQueriesQL.js.
Is there anything wrong the way I pass arguments on the resolve functions?
user: {
type: UserType,
args: {
username: {
name: 'username',
type: new GraphQLNonNull(GraphQLString)
}
},
resolve: function(parentValue, args) {
return User.find( args ).exec();
}
As I am beginner into GraphQL, even I ran into this issue. After going through each file individually I found that I forgot to import into my resolvers
import User from './User';
**import Post from './Post';**
const resolvers = [User, **Posts**];
Maybe this will help!
user: {
type: UserType,
args: {
username: { type: new GraphQLNonNull(GraphQLString) }
},
resolve: function(parentValue, args) {
return User.find( args ).exec(); // User.find({username: 'some name'}).exec();
// will work as matches your mongoose schema
}
Previously, in the args you are providing an an object with nested object username so,
args: { // this won't match your mongoose schema field as it's nested object
username: {
name: 'username',
type: new GraphQLNonNull(GraphQLString)
}
}
so when the user queries and provides args then
your args would be { username: { name: 'abcd' } }
// args = {username: {name: 'abcd'}}
and resolve() is executing User.find({username: {name: 'abcd'}}).exec();
/* searching for username{} object, but
your mongoose schema is username: String */
which doesn't match your database fields, which will always return an empty array [],also which will not match your GraphQL field type, as it is GraphQLNonNull
after viewing the gist the problem is with rootquery
the problem is with rootquery
let RootQuery = new GraphQLObjectType({
name: 'RootQueryType',
fields: () => ({
users: { type:UserQueries.users, resolve: UserQueries.users }
user: { type: UserQueries.user, resolve: UserQueries.user }
})
});
I have the following mongoose schema:
var ChatSchema = new Schema({
pin: String,
users: [{type: mongoose.Schema.Types.ObjectId, ref: "User"}],
messages: [{type: mongoose.Schema.Types.ObjectId, ref: 'Message'}], //<----
active: Boolean,
});
var MessageSchema = new Schema({
sent: Date,
user: {type: mongoose.Schema.Types.ObjectId, ref: 'User'},
content: String
});
var UserSchema = new Schema({
name: String,
pin: String,
id: String
});
This function is defined for the ChatSchema:
ChatSchema.methods.addMessageForUser = function(message, userid, userpin ) {
chat = this;
module.exports.User.findOne({id: userid, pin: userpin}).populate('messages').exec(function(err, user) {
message = {
user: user,
time: new Date(),
message: message,
};
chat.messages.push(message);
chat.save();
});
};
When I run it, I get the following error:
CastError: Cast to ObjectId failed for value "[object Object]" at path "messages"
If I remove populate('messages);` Then the error goes away, but I get another error because I try to use the messages array.
Here is the code for the models:
module.exports.Message = mongoose.model('Message', MessageSchema);
module.exports.User = mongoose.model('User', UserSchema);
module.exports.Chat = mongoose.model('Chat', ChatSchema);
Based on what you've got here, you're trying to populate backwards.
If each User had an array of Messages, then this populate call would work. It's a method on the mongoose Query object, in this case, and so it's looking for a property called messages on the documents in the User collection you're querying to pull ids from - since these aren't there, you get a weird error.
Based on what you've got here, it looks like it will work if you just remove the populate call.