After executing Customer.create({customerName: 'John'}), the following document is created without error and without the 'customerName' node.
Can anyone tell me why this seemingly simple document creation call yields a semi-blank document? The document in the response from Mongoose is the same as it is in the database itself.
I can't tell if I'm using Mongoose incorrectly or Express incorrectly. Thanks in advance for your help.
{ __v: 0, _id: 5452dc48d687bad849d70816 }
routes/customer.js
var mongoose = require( 'mongoose' );
var Customer = mongoose.model( 'Customer');
exports.create = function(req, res) {
Customer.create({
customerName: 'John'
}, function(err, customer) {
if (err) return err;
console.log('Customer created', customer);
res.send(customer);
});
}
schema/customer.js
var mongoose = require('mongoose');
var customerSchema = new mongoose.Schema({
customerName: {
type: String,
required: false
}
});
db.js
var mongoose = require( 'mongoose' );
var dbURI = 'mongodb://localhost/CustomerDatabase';
mongoose.connect(dbURI);
var customerSchema = require( '../schema/customer.js' );
var Customer = mongoose.model( 'Customer', customerSchema);
routes.js
function SetupRoutes(app, PATH) {
var db = require('../model/db.js')
var customer = require( '../routes/customer.js' );
app.post('/Customer', customer.create);
}
module.exports.SetupRoutes = SetupRoutes;
You need to export customerSchema from customer.js so that when db.js requires that file, its value is the exported schema:
var mongoose = require('mongoose');
var customerSchema = new mongoose.Schema({
customerName: {
type: String,
required: false
}
});
module.exports = customerSchema;
However, the more typical pattern is to create the model in customer.js and then export that:
var mongoose = require('mongoose');
var customerSchema = new mongoose.Schema({
customerName: {
type: String,
required: false
}
});
module.exports = mongoose.model('Customer', customerSchema);
Related
Below is the code I am trying: index.jsand its not working while changing the password in terms of salt and hash.(saving them in database) I am keep getting the error as setPassword is not defined. Also I think I am committing code errors as well. I want the exact route code for change password using 'passport-local' Strategy.
P.S. I am able to successfully register the user and login as well. I just want to give him the option to change the password.
var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
User.findOne({id: req.user.id}, function (err, data) {
console.log("came inside api changePassword else condition inside User.findOne");
if (err) {
console.log(err);
}
else {
data.setPassword(req.body.newPass, function(err,datas){
if(datas) {
data.save(function (err,datass) {
if (err) {
res.render('settingsClient', {errorMessages: err});
} else {
console.log("Hash and Salt saved");
}
});
}
else {
console.log("setPassword error"+ err);
}
});
}
})
This is
Models (user.js) with which I am saving the password at the start of registration of user as hash and salt.
var mongoose = require('mongoose');
var crypto = require('crypto');
var userSchema = new mongoose.Schema({
email: {
type: String,
unique: true,
required: true
},
name: {
type: String,
required: true
},
hash: String,
salt: String
});
userSchema.methods.setPassword = function(password) {
this.salt = crypto.randomBytes(16).toString('hex');
this.hash = crypto.pbkdf2Sync(password, this.salt, 1000, 64, 'sha1').toString('hex');
};
userSchema.methods.validPassword = function(password) {
var hash = crypto.pbkdf2Sync(password, this.salt, 1000, 64, 'sha1').toString('hex');
return this.hash === hash;
};
module.exports = mongoose.model('User', userSchema);
My goal is to build an app that will connect different professionals from different background. I'm also using mongoose as my database.
I created a profile.js that will create and update profiles. But when I test with postman, I get the following error:
"PROFILE VALIDATION FAILED: HANDLE: PATH HANDLE IS REQUIRED."
What can I possibly do to solve this issue?
Your help will be grateful.
const express = require('express'); // require express modules
const router = express.Router(); // to use express router
const auth = require('../../middleware/auth');
const { check, validationResult } = require('express-validator');
const Profile = require('../../models/Profile');
const User = require('../../models/User');
//#route GET api/profile/me
//#desc Get current users profile
//#access Private
router.get('/me', auth, async (req,res) => {
try{
const profile = await Profile.findOne({user: req.user.id}).populate(
'user',
['name', 'avatar']);
if(!profile){
return res.status(400).json({ msg:'No profile exists for this user'});
}
res.json(profile);
} catch(err){
console.error(err.message);
res.status(500).send('Server error');
}
}); //to create a route
//#route POST api/profile
//#desc Create or update users profile
//#access Private
router.post('/',
[
auth,
[
check('status', 'Status is required')
.not()
.isEmpty(),
check('skills', 'Skills is required')
.not()
.isEmpty()
]
] ,
async (req, res) =>{
const errors = validationResult(req);
if(!errors.isEmpty()){
return res.status(400).json({errors: errors.array()})
}
const {
company,
website,
location,
bio,
status,
githubusername,
skills,
youtube,
facebook,
twitter,
instagram,
linkedin
} =req.body;
//to build profile object
const profileFields = {};
profileFields.user = req.user.id
if(company) profileFields.company = company;
if(website) profileFields.website = website;
if(location) profileFields.location = location;
if(bio) profileFields.bio = bio;
if(status) profileFields.status = status;
if(githubusername) profileFields.githubusername = githubusername;
if(skills){
profileFields.skills = skills.split(',').map(skills => skills.trim());
}
//for the social object
profileFields.social = {}
if(youtube) profileFields.social.youtube = youtube;
if(facebook) profileFields.social.facebook = facebook;
if(twitter) profileFields.social.twitter = twitter;
if(instagram) profileFields.social.instagram = instagram;
if(linkedin) profileFields.social.linkedin = linkedin;
try{
let profile = await Profile.findOne({ user: req.user.id });
if(profile){ //if there is a profile, we will update it
profile = await Profile.findOneAndUpdate(
{ user: req.user.id},
{$set: profileFields },
{new: true}
);
return res.json(profile);
}
//this will create profiles
profile = new Profile(profileFields);
await profile.save();
res.json(profile);
} catch(err){
console.error(err.message);
res.status(500).send('Server Error');
}
}
);
module.exports = router;
same code, same issue. In the profile Schema there is a handle field that is set to required. i commented it out and it is working fine now.
the same code you made i made it,you will found handle is required in profile model delete it and your code will working
handle: {
type: String,
required: true,
max: 40
}
Change this code in your models/Profile.js to
handle: {
type: String,
required: false,
max: 40
},
I had the very same Issue . However , it happened because in your "Profile" Schema you probably you made the 'handle' attribute required . So , you must have to give it otherwise just make a change and make the require value to false . Such as (require: false) and hopefully your issue will go .
This is happening because your Profile schema has a handle field(attribute) in which you have a property required: true.
Go to the profile schema file and remove the handle attribute(field) or remove the required: true< from the handle attribute
Example
Profile.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
// Create Schema
const Profile = new Schema({
...,
handle: {
type: ...,
required: true //remove this line
}
...
});
use
let const profileFields = {};
profileFields.user = req.user.id
that's
let profileFields = {};
profileFields.user = req.user.id
or you can use
const profileFields = {};
profileFields.user = req.user.id;
I've got an Express/Mongoose app that keeps throwing "cyclic dependency detected" errors at me. I've localized the problem to one of these files.
app.js
var express = require('express');
var mongoose = require('mongoose');
mongoose.connect('mongodb+srv://username:MY.PASSWORD#cluster0-6vlss.mongodb.net/test?retryWrites=true');
require('./models/Users');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var app = express();
routes/users.js
var mongoose = require('mongoose');
var express = require('express');
var router = express.Router();
var User = mongoose.model('User');
router.route('/user/:id')
.get((req, res, next) => {
User.findById(req.params.id, (err, user) => {
if (err) return next(err);
res.json(user);
});
});
models/Users.js
var mongoose = require('mongoose');
var UserSchema = mongoose.Schema({
_id: String,
username: {type: String, unique: true},
hash: String,
salt: String,
chats: Array
});
var User = mongoose.model('User', UserSchema);
module.exports = User;
Hopefully I condensed my code well enough. Could somebody point to my screw-up?
Got it. In app.js, dbconfig is an object that stores the database URI string. I called "dbconfig" directly instead of "dbconfig.url". Everything's good now.
I have this codes:
// Morosos.js
var mongoose = require('mongoose');
const MorososSchema = new mongoose.Schema({
idlor: String,
comunidad: String,
vivienda: String,
demandado: String,
importe: String,
datos: [{ fecha: String, dato: String }],
date: { type: Date, default: Date.now },
});
mongoose.model('Morosos', MorososSchema);
module.exports = mongoose.model('Morosos');
&&
// MorososController.js
var express = require('express');
var router = express.Router();
var bodyParser = require('body-parser');
router.use(bodyParser.urlencoded({ extended: true }));
var Morosos = require('./Morosos');
router.post('/', function (req, res) {
console.log(req.body.datos.fecha + " " + req.body.comunidad);
Morosos.create({
idlor : req.body.idlor,
comunidad : req.body.comunidad,
vivienda : req.body.vivienda,
demandado: req.body.demandado,
importe: req.body.importe,
datos: [{fecha: req.body.datos.fecha, dato: req.body.datos.dato}] ,
date: Date.now()
},
function (err, user) {
if (err) return res.status(500).send("There was a problem adding the information to the database. Error: "+err);
res.status(200).send(user);
});
});
// RETURNS ALL THE USERS IN THE DATABASE
router.get('/', function (req, res) {
Morosos.find({}, function (err, users) {
if (err) return res.status(500).send("There was a problem finding the users. Error: ");
res.status(200).send(users);
});
});
module.exports = router;
When I use "POST" on "Postman" with x-www-form-urlencoded with this info:
idlor:LOR02/16
comunidad:XXXXX
vivienda:XXXXX
demandado:YYYYY
importe:XXXXX€
datos:{[fecha:28/09/2016,dato:Cristina]}
After trying lot of different ways I can't save the "array" datos or show the "array" datos on the server.
I put a code console.log(req.body.datos.fecha + " " + req.body.comunidad); but it throw me undefined at req.body.datos.fecha.
I'm blocked and I don't know how to solve this. Thanks!
Try sending:
idlor:LOR02/16
comunidad:XXXXX
vivienda:XXXXX
demandado:YYYYY
importe:XXXXX€
datos[fecha]:28/09/2016
datos[dato]:Cristina
I am developing a web application based on the Mean Stack, but I have a care with Add and Edit operations, particularly with sub documents of the Field "order", the console tells me that "reference" is undefined on the line "order.reference" : req.body.order.reference,
, I don't know how to for sub documents. When I add or modify any of "order" fields I got an error, but when I add all the Fields without exception it works. here is my mongoose diagram:
var mongoose = require('mongoose')
, Schema = mongoose.Schema;
var ContactSchema = new Schema({
name: {type: String},
order: {
reference : {type : String},
adresse : {type : String} ,
product : {type : String}
}
});
var ContactModel = mongoose.model('Contact', ContactSchema);
mongoose.connect('mongodb://localhost/contact');
exports.add = function(req, res) {
var contact = req.body;
contact = new ContactModel({
name: req.body.name,
"order.reference" : req.body.order.reference,
"order.adresse" : req.body.order.adresse,
"order.product" : req.body.order.product
});
contact.save(function (err) {
if (!err) {
res.json(true);
} else {
console.log(err);
res.json(false);
}
});
return res.jsonp(req.body);
};
exports.edit = function (req, res) {
var id = req.params.id;
if (id) {
ContactModel.findById(id, { upsert: true }, function (err, contact) {
contact.name = req.body.name,
contact.order.reference = req.body.order.reference,
contact.order.adresse = req.body.order.adresse ,
contact.order.product = req.body.order.product
contact.save(function (err) {
if (!err) {
res.json(true);
} else {
res.json(false);
console.log(err);
}
});
});
}
};
Thank you for your time, I can provide angular code and html
You'll probably want to use Express and the body parser:
How do you extract POST data in Node.js?
Note: I believe this was written for Express 3 and the syntax is a little different for Express 4