Mongoose gives validation error even if i give the correct create arguments. Checked, function just works one time & variables are not null.
Note: There are several models imported to file with same architecture of Payment Model.
await payment.create({
userId: user._id,
paymentDetails: session
})
Payment Model:
const mongoose = require('mongoose')
const { Schema } = mongoose
mongoose.connect('<REDACTED>')
const Payments = new Schema({
id: String,
userId: { type: String, required: true },
paymentDetails: {type: Object, required: true},
})
module.exports =
mongoose.models.Payments || mongoose.model('Payments', Payments)
Related
I'm using Passport Local Mongoose to create a user on my database. My goal is to allow users with the same username to register into my app. On my research, i found that if i pass an object as option on my Schema.plugin with 'usernameUnique: false', i would allowed users to register with the same username. The only problem is when a try it to make a register, i get an "UserExistsError" on my console.
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const passportLocalMongoose = require('passport-local-mongoose');
const UserSchema = new Schema({
email: {
type: String,
required: true,
},
username: {
type: String,
required: true,
unique: false
},
});
const options = {
usernameUnique: false,
}
UserSchema.plugin(passportLocalMongoose, options);
const User = mongoose.model('User', UserSchema);
module.exports = User;
I am trying to import a schema file(order.js) inside user.js from "models" folder.
My application gets crashed after saving user.js, it throws an error as follows,
"TypeError: Invalid value for schema path product.type, got value "undefined""
In user.js, I have imported order.js as follows,
const User = require("../models/user");
const Order = require("../models/order"); //Throws error on this line.
But when I comment require("../models/order") line, app starts to perform well.
This is my multiple Schema file (order.js):
const mongoose = require("mongoose");
const { Objectid } = mongoose.Schema;
const productCartSchema = new mongoose.Schema({
product: {
type: Objectid,
ref: "Product",
},
name: String,
count: Number,
price: Number,
});
const ProductCart = mongoose.model("ProductCart", productCartSchema);
const orderSchema = new mongoose.Schema(
{
products: [productCartSchema],
transactionid: {},
address: String,
amount: { type: Number },
updated: Date,
user: {
type: Objectid,
ref: "User",
},
},
{ timestamps: true }
);
const Order = mongoose.model("Order", orderSchema);
module.exports = { Order, ProductCart };
I have found a solution on this issue.
The ObjectId in my order.js is not defined. I just replaced it with mongoose.Schema.Types.ObjectId
This solved my issue.
I'm new to Express/Mongoose and backend development. I am attempting to use a Mongoose subdocument in my Schema and POST data from a form to an MLab database.
I am successfully POSTing to the database when only using the parent Schema, but when I attempt to also POST data from the subdocument I am getting an undefined error. How do I properly POST data from a subdocument?
Here is my Schema:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const bookSchema = new Schema({
bookTitle: {
type: String,
required: true
},
author: {
type: String,
required: true
},
genre: {
type: String
}
});
const userSchema = new Schema({
name: String,
username: String,
githubID: String,
profileUrl: String,
avatar: String,
// I've tried this with bookSchema inside array brackets and also
//without brackets, neither works
books: [bookSchema]
});
const User = mongoose.model('user', userSchema);
module.exports = User;
Here is my route where I attempt to POST to the database:
router.post('/', urlencodedParser, (req, res) => {
console.log(req.body);
const newUser = new User({
name: req.body.name,
username: req.body.username,
githubID: req.body.githubID,
profileUrl: req.body.profileUrl,
avatar: req.body.avatar,
books: {
// All of these nested objects in the subdocument are undefined.
//How do I properly access the subdocument objects?
bookTitle: req.body.books.bookTitle,
author: req.body.books.author,
genre: req.body.books.genre
}
});
newUser.save()
.then(data => {
res.json(data)
})
.catch(err => {
res.send("Error posting to DB")
});
});
Figured it out. I wasn't properly accessing the values using dot notation.
books: {
// All of these nested objects in the subdocument are undefined.
//How do I properly access the subdocument objects?
bookTitle: req.body.books.bookTitle,
author: req.body.books.author,
genre: req.body.books.genre
}
No need to access .books inside of the books object. req.body.books.bookTitle should be req.body.bookTitle and so forth. Leaving this post up in case it helps someone else.
I am building a web application in Node with two different types of user. And both of them will have common as well as different properties.
The problem is I am unable to use the common mongoose schema model in another model.
user.js is the common model with the following schema :
//Requiring Mongoose
const mongoose = require('mongoose');
//Creating a variable to store our Schemas
const Schema = mongoose.Schema;
//Create User Schema and Model
const UserSchema = new Schema({
email: {
type: String,
required: [true, 'Email Field is required'],
unique:true,
match: /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/
},
name: {
type: String,
required: [true, 'Name field is required']
},
password: {
type: String,
required: [true, 'Please enter your password']
},
phoneNo: {
type: String,
required: [true, 'Phone No is required']
}
//Create a user model which is going to represent our model in the database
and passing our above-created Schema
const User = mongoose.model('user', UserSchema);
//Exporting Models
module.exports = User;
Now I want to use the same UserSchema in another model file rider.js with another property familyNo
I have tried following way but it failed.
//Requiring Mongoose
const mongoose = require('mongoose');
//Importing user Schema to remove the code redundancy
const userSchema = require('./user');
//Creating a variable to store our Schemas
const Schema = mongoose.Schema;
//Create Driver Schema and Model
const RiderSchema = new Schema({
user: userSchema
familyNo: {
type: String,
required: [true, 'Name field is required']
}
});
//Create a rider model is going to represent our model in the database and passing our above-created Schema
const Rider = mongoose.model('rider', RiderSchema);
//Exporting Models
module.exports = Rider;
the problem is you are not passing the schema , you are passing the user model , move your userschema in different file , and use it as schema in both the models , that will solve the problem
//Create a user model which is going to represent our model in the database and passing our above-created Schema
const User = mongoose.model('user', UserSchema);
//Exporting Models
module.exports = User; // Here is the problem, User is a model not schema
UserSchema.js
const UserSchema = mongoose.Schema([Your Common Schema])
User.js
var userSchema = require('./UserSchema');
module.exports = mongoose.model('User', userSchema);
OtherModel.js
var userSchema = require('./UserSchema');
module.exports = mongoose.model('OtherModel' , {
property : String,
user : userSchema
});
I'm trying to link my mlab with my models but it's throwing me an error like this:
throw new TypeError('Undefined type ' + name + 'at' + path +
^
TypeError: Undefined type undefined at required
Did you try nesting Schemas? You can only nest using refs or arrays.
In my folder models I've got:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const ProjectSchema = new Schema({
name: String,
email: String,
description: String,
image: {data: Buffer, contentType: String },
date: { type: Date, default: Date.now },
location: String, //{street: String, number: String, zip: String, city: String, required: true},
fixedAmount: Number, required: true,
wantedAmount: Number,
receivedAmount: Number
});
module.exports = mongoose.model('Project', ProjectSchema);
and almost the same with my UserSchema...
I have also an index.js there :
const mongoose = require('mongoose');
module.exports.connect = (uri) => {
mongoose.connect(uri);
// plug in the promise library:
mongoose.Promise = global.Promise;
mongoose.connection.on('error', (err) => {
console.error(`Mongoose connection error: ${err}`);
process.exit(1);
});
// load models
require('./user');
require('./project');
require('./common');
};
In my server.js :
const config = require('./config.js');
// connect to the database and load models
require('./server/models').connect(config.dbUrl);
and in my config.js:
const dotenv = require('dotenv').config();
module.exports = {
'port': process.env.PORT || 5000,
'dbUrl': `mongodb://${process.env.USER_DB}:${process.env.PASSWORD_DB}#ds123930.mlab.com:23930/kickass`,
"jwtSecret": "a secret phrase !"
}