add a user into collection in Mongodb - javascript

I have a collection named users and I'm trying to add a user to the collection the code I'm using is
var user1 = {
Username: "joonyoftv",
Password: "joon123",
Email: "joony#bmail.com",
Birthday: {
new Date: ( "2000-08-02")
},
FavoriteMovies: [ 61942e53b8d3d951230f0980, 61943aabb8d3d951230f0983 ]
}
but i keep on getting an error that says SyntaxError: missing : after property id :
#(shell):6:7
What should i do?

It's just a simple JavaScript syntax error!
The new Date: ( "2000-08-02")" should not be in curly braces and ids in FavoriteMovies array should be enclosed in string literals.
Object with correct syntax:
var user1 = {
Username: "joonyoftv",
Password: "joon123",
Email: "joony#bmail.com",
Birthday: new Date("2000-08-02"), // corrected
FavoriteMovies: ["61942e53b8d3d951230f0980", "61943aabb8d3d951230f0983"],
//String ^ ^ ^ ^
};

Related

Yup keeps running validators on the same property when .required() is false

I'm a bit confused about how yup is working.
I have the following schema to validate the register
export const registerValidationSchema = yup.object().shape({
first_name: yup.string().trim().required(),
last_name: yup.string().trim().required(),
date_of_birth: yup.date().required().test('DOB', 'You must be at least 18 to register', value => {
return value.setFullYear(value.getFullYear() + 18) < Date.now()
}),
email: yup.email().trim().required()
});
When the object to validate is the following
const data = {
email: "john.doe#company.com"
}
The validation will crash because value is undefined and the function value.setFullYear will fail. But why? I assume that yup will stop this line on .required() part and go to the next property.
I know the issue can be fixed by adding if(!value) return false; inside .test() but what's the point of the required function?
From the yup documentation:
string.required(message?: string | function): Schema
The same as the mixed() schema required, except that empty strings are also considered 'missing' values.
mixed.required(message?: string | function): Schema
Mark the schema as required, which will not allow undefined or null as a value. Note that unless a schema is marked as nullable() a null value is treated as a type error, not a missing value. Mark a schema as mixed().nullable().required() treat null as missing.
So I read this as an undefined, null or '' value should fail on the .required() rule.
Instead of email: yup.email().trim().required()
Try email: yup.string().trim().email().required()
found in github documentation
const registerValidationSchema = yup.object().shape({
first_name: yup.string().trim().required(),
last_name: yup.string().trim().required(),
date_of_birth: yup.date().required().test('DOB', 'You must be at least 18 to register', value => {
return value.setFullYear(value.getFullYear() + 18) < Date.now()
}),
// email: yup.email().trim().required
// modified
email: yup.string().trim().email().required()
})
const data = {
first_name: "john",
last_name: "deo",
date_of_birth: "12-jan-2000",
email: " john.doe#gamil.com "
}
// validating schema
registerValidationSchema.isValid(data)
.then(r => console.log(r))
.catch(e => console.log(e))

Typescript error on converting type into different type

I'm just trying to know following error better:
Conversion of type 'A' to type 'B' may be a mistake because neither
type sufficiently overlaps with the other.
Then when I tried to do some tests, I got a weird error.
These our my codes:
type User = {
id: string
username: string
age?: number
}
const user1 = {
id: '123',
username: 'user',
} as User // OK
const user2 = {
id: '123',
username: 'user',
age: 5
} as User // OK
const user3 = {
id: '123',
username: 'user',
age: 5,
email: '1234'
} as User // OK
const user4 = {
id: '123',
username: 'user',
age: '5',
} as User // Error, the age type is different
These tests look straight forward.
But when I tried these:
const user5 = {
username: 'user',
age: 5,
} as User // OK even though the ID is not exist
// Weird part
const user6 = {
username: 'user',
age: 5,
email: '123'
} as User // Error, when we add unknown field without Id field
`
Based on the user5, the assertion is correct. But in user6 it doesn't which I didn't understand. Can someone here help me to understand whats going on? Thanks.
Unless TypeScript strict null checks are enabled, null and undefined can be assigned to any type. In your user5 test id is undefined implicitly and the compiler is happy with that.

Cast to Array failed when insertind data to mongodb via express.sj

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

Why is save not a function after assigning properties?

TypeError: newUser.save is not a function (in the createNew function)
Before assigning the properties with the spread operator, the userModel object has a save function (as designed by mongoose), however after the assign the function cannot be accessed anymore. Can someone explain why this is and how to get around it?
const mongoose = require('mongoose')
const UserSchema = new mongoose.Schema({
facebookid: String,
firstname: String,
lastname: String,
email: String,
timezone: Number,
gender: String,
invitationid: String,
referralid: String,
locale: String,
stage: String
})
const User = mongoose.model('User', UserSchema)
const createUser = () => new User()
module.exports = {
createNew : userInfo => {
const userModel = createUser()
const newUser = { ...userModel,
facebookid: userInfo.fid,
firstname: userInfo.first_name,
lastname: userInfo.last_name,
locale: userInfo.locale,
timezone: userInfo.timezone,
gender: userInfo.gender,
invitationid: userInfo.invitationid,
referralid: userInfo.referralid,
stage: 'NA'
}
return newUser.save()
}
}
Thanks for the help!
Mate
You can pass object while creating new user :-
module.exports = {
createNew : userInfo => {
const userModel = createUser({
facebookid: userInfo.fid,
firstname: userInfo.first_name,
lastname: userInfo.last_name,
locale: userInfo.locale,
timezone: userInfo.timezone,
gender: userInfo.gender,
invitationid: userInfo.invitationid,
referralid: userInfo.referralid,
stage: 'NA'
})
return userModel.save()
}
}
And Modify
createUser = (user) => new User(user)
Now the userModel contains the user returned by mongoose orm and you can access save function.Earlier you weren't using the user object returned by mongoose, you were creating new one
Actually your newUser is not a User object.
...userModel will only merge object "own" properties not the prototype.
Try something like this :
const newUser = new User({/* your user */});
newUser.save();
Just as a detail, concerning the problem and not a possible solution
with {...userModel} you're copying the direct properties of the User instance into a plain object. Any property or method inherited from extended classes will be ignored and, most importantly, the prototype chain itself will be lost.
the save() method is probably defined in the Schema class from moongoose, so you lose it with that technique.
Any of the proposed solutions in the other answers will fix the problem just fine.

Array of ObjectIds will not populate without error

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.

Categories