We are trying to figure out how get the data from the database but the result get "null"
the model
const mongoose = require("mongoose");
const ClubSchema = new mongoose.Schema({
nomClub: String,
classement: String,
dateMatch: String,
classementDB: String,
logo: String,
adversaire: String,
});
const SportSchema = new mongoose.Schema({
nom: String,
clubs: [ClubSchema],
});
module.exports = mongoose.model("sport", SportSchema);
and the back
getSportAdversaire: (req, res) => {
Sport.findOne({ "clubs.nomClub": "Stade Rennais" }, (err, data) => {
if (err) {
console.log(err);
res.json({ message: "une erreur s'est produite" });
} else {
res.json(data);
console.log(data);
}
});
},
You dont need to use the key as clubs.nomClub. You can simply use the key as nomClub. Your key name is nomClub and not clubs.nomClub.
sport.findOne({ "nomClub": "Stade Rennais" }, (err, data) => {
if (err) {
console.log(err);
res.json({ message: "une erreur s'est produite" });
} else {
res.json(data);
console.log(data);
}
});
Related
I'm trying to write a user image to a nodejs + sequelize + sqlServer server.
The first part of the function is to record the image to the server the complete one correctly.
But I can't save the filename in the img field of the database.
In postman gives me code 200 but then cool I make a get to the user not to record the filename in the field.
Thanks in advance.
app.put('/upload/:tipo/:idUsuario', upload.single('imagen'), (req, res) => {
try {
res.send(req.file);
const { tipo, idUsuario } = req.params;
usuariosModel.findOne({ where: { idUsuario: idUsuario } })
.then(updateimg => {
updateimg.update({ img: req.file.filename })
.then(() => {
res.status(200).send({ updateimg });
})
.catch(error => {
res.status(500).send({ msg: 'OcurriĆ³ un error al actualizar el usuario' });
})
})
.catch(error => {
console.log(error);
});
} catch (err) {
console.log(err);
}
});
user.js : model
"use strict";
const { Model } = require("sequelize");
module.exports = (sequelize, DataTypes) => {
class user extends Model {
}
user.init({
name: { type: DataTypes.STRING, },
img: { type: DataTypes.STRING, },
}, {
sequelize,
modelName: "user",
defaultScope: {
attributes: { exclude: ["createdAt", "updatedAt"] }
}
});
return user;
};
router.js
router.put('/upload/:idUsuario', upload.single('imagen'), (req, res) => {
try {
// res.send(req.file); // must comment this
const { idUsuario } = req.params;
db.user.findOne({ where: { id: idUsuario } })
.then(updateimg => {
updateimg.update({ img: req.file.filename })
.then(() => {
res.status(200).send({ updateimg });
})
.catch(error => {
res.status(500).send({ msg: 'OcurriĆ³ un error al actualizar el usuario' });
})
})
.catch(error => {
console.log(error);
});
} catch (err) {
console.log(err);
}
});
https://github.com/nkhs/node-sequelize/blob/stack-66495393/api/routes/game.js
I tested this with post man
http://prntscr.com/10dt3jq
http://prntscr.com/10dt4o8
I am doing APIs and Microservices projects on FreeCodeCamp,the "Url shortener microservice". Here is my code:
const shorturlSchema = mongoose.Schema({
originalUrl: String,
shortUrl: Number
});
const ShortUrl = mongoose.model("ShortUrl", shorturlSchema);
app.post("/api/shorturl/new", urlencodedParser, async (req, res) => {
var url = req.body.url;
console.log(url);
if (!validUrl.isWebUri(url)) {
res.json({ error: "invalid url" });
} else {
var newUrl = new ShortUrl({
originalUrl: url,
shortUrl: shortId.generator
});
try {
await newUrl.save();
} catch (err) {
console.log("error", err);
return res.json({
error: "failed to store in database"
});
}
res.json({
"origianl_url": newUrl.originalUrl,
"short_url": shortId.generate
});
}
});
app.get("/api/shorturl/:short_url?", async (req, res) => {
console.log(req.params.short_url);
const smallUrl = req.params.short_url;
if (smallUrl === undefined) res.json({ error: "undefined" });
else {
const actualUrl = await ShortUrl.findOne({ shortUrl: smallUrl });
res.redirect(actualUrl.originalUrl);
return;
}
});
It should respond with a {"original_url":"www.google.com","short_url":1}. But instead it shows {"origianl_url":"https://www.freecodecamp.org". What am I doing wrong here?
You could pass the shortUrl from the database object.
Edited code:
try {
const response = await newUrl.save();
return res.json({
"origianl_url": response.originalUrl,
"short_url": response.shortUrl
});
} catch (err) {
return res.json({
error: "failed to store in database"
});
}
Actually I made some changes in the code. In the schema:
const shorturlSchema = mongoose.Schema({
originalUrl: String,
shortUrl: {
type:String,
default:shortId.generate
}
});
Then in the app.post section
var newUrl = new ShortUrl({
originalUrl: url
});
Then finally in the res.json part of app.post
res.json({
"original_url": newUrl.originalUrl,
"short_url": newUrl.shortUrl
});
This gives me the output:
{"original_url":"https://www.freecodecamp.org","short_url":"_sAInwNXs"}
I just figured this out now. Thanks for all your help
How can I add object to my nested Array in PartnerSchema?
I separate documents, because in the future there will be more of nested arrays.
This is my schema:
var productSchema = new mongoose.Schema({
name: String
});
var partnerSchema = new mongoose.Schema({
name: String,
products: [
{
type: mongoose.Schema.Types.ObjectId,
ref: 'Product'
}]
});
module.exports = {
Partner: mongoose.model('Partner', partnerSchema),
Product: mongoose.model('Product', productSchema)
}
And this is my backend:
var campSchema = require('../model/camp-schema');
router.post('/addPartner', function (req, res) {
new campSchema.Partner({ name : req.body.name }).save(function (err, response) {
if (err) console.log(err);
res.json(response);
});
});
router.post('/addProduct', function (req, res) {
campSchema.Partner.findByIdAndUpdate({ _id: req.body.partnerId },
{
$push: {
"products": {
name: req.body.dataProduct.name
}
}
}, { safe: true }, function (err, response) {
if (err) throw err;
res.json(response);
});
});
I can add Partner by using /addPartner and it works fine.
Problem is with second function /addProduct I can't add Product to Array in Partner Schema. I have an error: CastError: Cast to undefinded failed for value "[object Object]" at path "products"
Since the products field in Partner model is an array that holds _id refs to the Product model, you are supposed to push an _id to the array, not an object hence Mongoose complains with an error.
You should restructure your code to allow the saving of the Product _id ref to the Partner model:
router.post('/addProduct', function (req, res) {
var product = new campSchema.Product(req.body.dataProduct);
product.save(function (err) {
if (err) return throw err;
campSchema.Partner.findByIdAndUpdate(
req.body.partnerId,
{ "$push": { "products": product._id } },
{ "new": true },
function (err, partner) {
if (err) throw err;
res.json(partner);
}
);
});
});
[TypeError: Cannot read property 'rid' of undefined]
Is the error that I get when I try to execute this controller on my post route.
I've tested it out with Postman.
I've tried to console.log(result) but I get undefined.
My query gets executed and my row is inserted into my table. I've checked it. Password is also hashed.
The problem is that I don't get any out binds that should be returned.
Problematic code (IMO) is
...
.then(function(result) {
console.log(result);
cb(null, {
id: result.outBinds.rid[0],
email: result.outBinds.remail[0],
role: result.outBinds.rrole[0]
});
})
...
oracle-NodeDB Wrapper
var oracledb = require('oracledb');
module.exports.OBJECT = oracledb.OBJECT;
function executeSQL(config ,sql, bindParams , options) {
return new Promise(function(resolve, reject) {
oracledb.getConnection(
config,
function(err, connection) {
if (err) {
return reject(err);
}
connection.execute(
sql,
bindParams,
options,
function(err, result) {
if (err) {
doRelease(connection);
return reject(err);
}
resolve(result);
doRelease(connection);
});
});
});
}
function doRelease(connection) {
connection.release(
function(err) {
if (err) {
console.log(err.message);
}
}
);
}
module.exports.executeSQL = executeSQL;
Controller
var database = require('../database/oracledbWrapper');
var dbconfig = require('../database/dbconfig').dbconfig;
var jwt = require('jsonwebtoken');
var bcrypt = require('bcrypt');
exports.createUser = function(req, res, next) {
var user = {
email: req.body.email
};
var unhashedPassword = req.body.password;
bcrypt.genSalt(10, function(err, salt) {
if (err) {
return next(err);
}
bcrypt.hash(unhashedPassword, salt, function(err, hash) {
if (err) {
return next(err);
}
user.hashedPassword = hash;
insertUser(user, function(err, user) {
var payload;
if (err) {
return next(err);
}
payload = {
sub: user.email,
role: user.role
};
res.status(200).json({
user: user,
token: jwt.sign(payload, config.jwtSecretKey, {expiresInMinutes: 60})
});
});
});
});
}
function insertUser(user, cb) {
var bindParams = {
email: user.email.toLowerCase(),
password: user.hashedPassword,
rid: {
type: database.NUMBER,
dir: database.BIND_OUT
},
remail: {
type: database.STRING,
dir: database.BIND_OUT
},
rrole: {
type: database.STRING,
dir: database.BIND_OUT
}
};
database.executeSQL(
dbconfig,
'insert into express_users (email, password, role ) values ( :email, :password, \'BASE\' ) returning id, email, role into :rid , :remail, :rrole',
bindParams,
{}
)
.then(function(result) {
console.log(result);
cb(null, {
id: result.outBinds.rid[0],
email: result.outBinds.remail[0],
role: result.outBinds.rrole[0]
});
})
.catch(function(err) {
console.log(err);
next(err);
});
}
Route
var RESTfulAPICon = require('../controllers/RESTfulAPI');
var indexCon = require('../controllers/index');
var views = require('express').Router();
views.route('/users').post(RESTfulAPICon.createUser);
exports.views = views;
The problem was in my wrapper , mainly here
module.exports.OBJECT = oracledb.OBJECT;
I export only the OBJECT property , but I try to access BIND_OUT properties later on. And they are non existent.
If I do the full export like this
module.exports.OBJECT = oracledb;
Then I can access BIND_OUT properties.
I'm building a MEAN app.
This is my Username schema, the username should be unique.
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
module.exports = mongoose.model('User', new Schema({
username: { type: String, unique: true }
}));
On my post route I save the user like this:
app.post('/authenticate', function(req, res) {
var user = new User({
username: req.body.username
});
user.save(function(err) {
if (err) throw err;
res.json({
success: true
});
});
})
If I post with the same username again I get this error:
MongoError: insertDocument :: caused by :: 11000 E11000 duplicate key
error index:
Can someone explain how instead of the error to send a json like { succes: false, message: 'User already exist!' }
Note: After I post the user I will automatically authentificate, dont need password or something else.
You will need to test the error returned from the save method to see if it was thrown for a duplicative username.
app.post('/authenticate', function(req, res) {
var user = new User({
username: req.body.username
});
user.save(function(err) {
if (err) {
if (err.name === 'MongoError' && err.code === 11000) {
// Duplicate username
return res.status(422).send({ succes: false, message: 'User already exist!' });
}
// Some other error
return res.status(422).send(err);
}
res.json({
success: true
});
});
})
You can also try out this nice package mongoose-unique-validator which makes error handling much easier, since you will get a Mongoose validation error when you attempt to violate a unique constraint, rather than an E11000 error from MongoDB:
var mongoose = require('mongoose');
var uniqueValidator = require('mongoose-unique-validator');
// Define your schema as normal.
var userSchema = mongoose.Schema({
username: { type: String, required: true, unique: true }
});
// You can pass through a custom error message as part of the optional options argument:
userSchema.plugin(uniqueValidator, { message: '{PATH} already exists!' });
2022 Update.
Looks like the err.name changed. Before, this error was returning as a MongoError, but now it is a MongoServerError. There's a whole story about Mongoose not handling MongoError directly, basically when a ServerError appears mongoose return it as it is.
NOTE: violating the constraint returns an E11000 error from MongoDB when saving, not a Mongoose validation error.## Heading ##
But now, this error is not a MongoError anymore, it's a MongoServerError now, which extends MongoError https://mongodb.github.io/node-mongodb-native/4.0/classes/mongoerror.html
Here two working examples:
app.post('/authenticate', function(req, res) {
var user = new User({
username: req.body.username
});
user.save(function(err) {
if (err) {
if (err.name === 'MongoServerError' && err.code === 11000) {
// Duplicate username
return res.status(422).send({ success: false, message: 'User already exist!' });
}
// Some other error
return res.status(422).send(err);
}
res.json({
success: true
});
});
})
async function store(req: Request, res: Response) {
const { email, password }: IUser = req.body;
const user: IUser = new User({
email: email,
password: await hashPassword(password),
});
user
.save()
.then(result => {
return res.status(201).json({
message: 'Successful registration.',
data: { email: result.email },
});
})
.catch(err => {
if (err.name === 'MongoServerError' && err.code === 11000) {
//There was a duplicate key error
return res.status(400).json({
message: 'Email already in use.',
data: { err },
});
}
return res.status(400).json({
message: "You didn't give us what we want!",
data: { err },
});
});
}
If you are using mongoose>4.5.0 you can use this error handling middleware based on their documentation:https://mongoosejs.com/docs/middleware.html#error-handling-middleware
//Checking for unique keys when you have multiple indexes
UserSchema.post("save", function (error, doc, next) {
if (error.name === "MongoServerError" && error.code === 11000) {
const keyPattern = Object.keys(error.keyPattern);
const key = keyPattern[0];
next(new Error(`${key} already taken!`));
} else {
next();
}
});
Here's how you validate it using the type error instead of string:
// your own error in a diff file
class UniqueError extends Error {
constructor(message) {
super(message)
}
}
// in your service file
const { MongoError } = require('mongodb')
class UserService {
async createUser(userJSON) {
try {
return await User.create(userJSON)
} catch (e) {
if (e instanceof MongoError && e.code === 11000) {
throw new UniqueError('Username already exist')
}
throw e
}
}
}
// in your controller file
class UserController {
async create(req, res) {
const userJSON = req.body
try {
return res.status(201).json(await userService.createUser(userJSON))
} catch (e) {
if (e instanceof UniqueError) {
return res.status(422).json({ message: e.message })
}
return res.status(500).json({ message: e.message })
}
}
}
Try this:
app.post('/authenticate', function(req, res) {
var user = new User({
username: req.body.username
});
user.save(function(err) {
if (err) {
// you could avoid http status if you want. I put error 500
return res.status(500).send({
success: false,
message: 'User already exist!'
});
}
res.json({
success: true
});
});
})