None of the already existing posts on Stackoverflow have remedied my issue. I have the following in the router:
const express = require("express");
const mongoose = require("mongoose");
const User = require("./users/models");
const app = express();
const router = express.Router();
mongoose.Promise = global.Promise;
app.use(express.json());
router.post("/add", (req, res) => {
const username = req.body.username;
console.log(username);
User.find({ username: username })
.then(user => res.json(user.serialize()))
.then(res => console.log(res));
});
module.exports = router;
with the following Schema:
const UserSchema = mongoose.Schema({
username: {
type: String,
required: true,
unique: true,
},
password: {
type: String,
required: true,
},
firstName: { type: String, default: "" },
lastName: { type: String, default: "" },
bases: [{ type: mongoose.Schema.Types.ObjectId, ref: "UserVariables" }],
});
const UserVariables = mongoose.Schema({
bases: { type: "String", required: true },
users: [{ type: String }],
});
const UserVariable = mongoose.model("UserVariable", UserVariables);
const User = mongoose.model("User", UserSchema);
module.exports = { User, UserVariable };
When running the server, the .find() method returns an error message stating: TypeError: User.find is not a function. I tried several different versions in the router:
router.post("/add", (req, res) => {
const username = req.body.username;
User.find({ username: username }, user => {
console.log(user);
});
as well as:
User.findOne({ username: username })
.then(user => res.json(user.serialize()))
.then(res => console.log(res));
});
Neither of which works. In another App i am running the former and it works just fine. Any ideas ?
You're exporting an object:
module.exports = { User, UserVariable };
So to use User.find(...) from your require, you should call User.User.find(...).
Have you tried exchanging User with UserVariable.
UserVariable.findOne({ username: username })
.then(user => res.json(user.serialize()))
.then(res => console.log(res));
});
use
module.exports=User=mongoose.model('User',UserSchema)
instead of
module.exports = router;
Related
I am completely Stuck tried everything possible but no luck to resolve this error
UnhandledPromiseRejectionWarning: CastError: Cast to ObjectId failed for value "register" at path "_id" for model "User"
i am using mongodb 4.2 and "mongoose": "^5.12.10"
Please anyone help me.
users_router.js
const { User } = require('../models/user_schema');
const express = require('express');
const router = express.Router();
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
router.get('/:id', async(req, res) => {
console.log(req.params.id);
const user = await User.findById(req.params.id).select('-passwordHash');
if (!user) {
res.status(500).json({ message: 'The user with the given ID was not found.' })
}
res.status(200).send(user);
})
router.post('/register', async(req, res) => {
let user = new User({
name: req.body.name,
email: req.body.email,
passwordHash: bcrypt.hashSync(req.body.password, 10)
})
console.log(user, "harman");
user = await user.save();
if (!user)
return res.status(400).send('the user cannot be created!')
res.send(user);
})
// This is Schema
user_schema.js
const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({
name: {
type: String,
required: true,
},
email: {
type: String,
required: true,
},
passwordHash: {
type: String,
required: true,
}
});
userSchema.virtual('id').get(function() {
return this._id.toHexString();
});
userSchema.set('toJSON', {
virtuals: true,
});
exports.User = mongoose.model('User', userSchema);
exports.userSchema = userSchema;
I'm pretty new to node and mongoose, still learning a lot. Basically I am trying to create a forum page. I have a forumpost schema and I have recently added in a new field that I would like to show which user posted it. I have read other questions on this online and I was able to follow the code on there however mine is still not working. When i check my data in atlas it is still missing the new 'submitted by' field that I added. I have already deleted the 'collection' and have started over but it is still missing. Any help would be appreciated. Heres my models below as well as a screencap of how the data is being posted to the db.
**Post Form Schema**
const mongoose = require('mongoose');
const PostSchema = new mongoose.Schema({
title: {
type: String,
required: true
},
body: {
type: String,
required: true,
},
date: {
type: Date,
default: Date.now,
required: true,
},
submittedBy: { *(this is where I would like to get the user who submitted the form)*
type: mongoose.Schema.Types.ObjectId,
ref: 'User',
},
extraInfo: {
type: String,
default: 'Other info goes here',
}
})
const Post = mongoose.model('Post', PostSchema);
module.exports = Post;
**Users Form Schema**
const mongoose = require('mongoose');
const UserSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
email: {
type: String,
required: true
},
password: {
type: String,
required: true
},
date: {
type: Date,
default: Date.now
}
});
const User = mongoose.model('User', UserSchema);
module.exports = User;
EDIT: heres my newpost route
const express = require('express');
const Post = require('../models/post');
const router = express.Router();
const {ensureAuthenticated} = require("../config/auth.js");
router.get('/', ensureAuthenticated, (req, res) => {
res.render('newPost')
})
router.post('/', ensureAuthenticated, (req, res) => {
const post = new Post(req.body);
console.log(req.body)
post.save()
.then((result) => {
res.redirect('/dashboard')
})
.catch((err) => {
console.log(err)
})
})
module.exports = router;
If I'm not mistaken, you validate if is authenticated with the "ensureAuthenticated" middleware (the user ID should be there) but when creating the "Post" you only do it with the body data.
It is something like this ( you should replace "userId" with your property name):
const post = new Post({ ...req.body, submittedBy: userId })
Client.js
const mongoose = require("mongoose");
var Schema = mongoose.Schema;
const clientSchema = new mongoose.Schema(
{
name: { type: String, required: true, default: "" },
}, {
timestamps: true
}
);
module.exports = mongoose.model("Client", clientSchema);
User.js
const mongoose = require("mongoose");
var Schema = mongoose.Schema;
const userSchema = new mongoose.Schema({
name: { type: String, required: true, default: "" },
clients: [{
client: {
type: Schema.Types.ObjectId,
ref: "Client",
default: null
},
user_group: {
type: Number
default: null
}
}]
}, { timestamps: true });
module.exports = mongoose.model("User", userSchema);
auth.js (Where trying to populate Clients)
const express = require("express");
const router = express.Router();
const User = require("../models/User");
const Client = require("../models/Client");
router.post("/users", (req, res) => {
let params = req.body;
let total_client = [];
User.findOne({
email: params.email
})
.populate({
path: "clients.client",
model: Client
})
.exec((err, user) => {
console.log(user);
res.send(user);
});
});
module.exports = router;
Please check the above code. I have given code examples of my two models user.js and client.js. In user schema, I have referenced client inside an array object. While querying user, the client is not population. Please help me to get this thing done. Thanks in advance.
The following expects you to provide a name in the json body of your post request (your example uses email which does not exist in the user model). Also, your model is already defining the ref: Client and so you can simplify your request to just include the path clients.client.
router.post("/users", async (req, res) => {
const { name } = req.body;
const user = await User.findOne({ name: name }).populate('clients.client').exec();
res.send(user);
});
Solved this problem just adding an extra parameter in module export of client.js file
module.exports = mongoose.model("Client", clientSchema, "client");
Having an issue with a model. Trying to do a model.findOne(), but I keep getting the error
TypeError: User.findOne is not a function
I have the model setup like so:
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const UserSchema = new Schema({
firstName: String,
lastName: String,
emailAddress: {
type: String,
required: true,
unique: true
},
userName: {
type: String,
required: true,
unique: true
},
password: {
type: String,
required: true
}
});
module.export = User = mongoose.model("User", UserSchema);
and I have it imported in the file that I want to find a user:
const { Strategy, ExtractJwt } = require("passport-jwt");
const log = require("./logger");
require('dotenv').config();
const fs = require("fs");
const secret = process.env.SECRET || 'thisneedstob3ch#ng3D';
const mongoose = require("mongoose");
const User = require("./models/user");
const opts = {
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: secret
};
module.exports = passport => {
passport.use(
new Strategy(opts, (payload, done) => {
User.findOne({id: payload.id})
.then(user => {
if (user) {
return done(null, {
id: user.id,
name: user.name,
email: user.email
});
}
return done(null, false);
})
.catch(err => log.error(err));
})
);
};
Regardless, I get the error. I've tried .findById() as well as .findOne()
Is there something I'm missing?
You made a typo in you user.js file, you forgot the s of module.exports:
module.exports = User = mongoose.model("User", UserSchema);
I'm connecting a Angular 2 app to MongoDB via Mongoose.
I'm trying to store some data, but i obtain an error on all required properties.
I set up a schema, serverside:
var mongoose = require("mongoose");
var Schema = mongoose.Schema;
var uniqueValidator = require("mongoose-unique-validator");
var schema = new Schema({
email: {
type: String,
required: true,
unique: true
},
password: {
type: String,
required: true
},
nome: {
type: String,
required: true
},
cognome: {
type: String,
required: true
},
dataNascita: {
type: Date
},
telefono: {
type: String
},
classifica: {
type: String
}
});
schema.plugin(uniqueValidator);
module.exports = mongoose.model("User", schema);
The user object is clearly filled:
Mongoose responds with an error:
Thanks in advance for any help.
Max
Update:
The call from a Angular service:
#Injectable()
export class AuthService {
constructor(private http: Http) {
}
addUser(utente: Utente) {
const body = JSON.stringify(utente);
return this.http.post('http://localhost:3000/utente', body)
.map((response: any) => {
console.log(response);
response.json();
})
.catch((error: Response) => Observable.throw(error.json()
));
}
}
The Moongose call:
var express = require('express');
var router = express.Router();
var User = require('../models/users');
router.post('/', function (req, res, next) {
var user = new User({
email: req.body.email,
password: req.body.password,
nome: req.body.nome,
cognome: req.body.cognome,
dataNascita: req.body.dataNascita,
telefono: req.body.telefono,
classifica: req.body.classifica
});
console.log(res);
user.save(function (err, result){
console.log(err);
console.log(res);
if (err){
return res.status(500).json({
titolo: "Errore durante il salvataggio",
errore: err
});
}
res.status(201).json({
messaggio: 'Utente salvato correttamente',
oggetto: res
});
});
});