Multer images array not store in mongoDB Database - mongodb

I am try to upload images on server and save image path in mongoDB database. but image path not stored in database your text
const UserSchema = new mongoose.Schema({
name: {type: String, required: true, trim: true },
email: {type:String, unique:true, required: true, trim: true, lowercase: true,
validate(value){
if(!validator.isEmail(value)){
throw new Error('Email is Invalid!')
}
}
},
password: {type: String, required:true, trim: true,minlength:7,
validate(value){
if(value.toLowerCase().includes('password')){
throw new Error('Password cannot conatin "password"')
}
}
},
age: {type: Number, required: true, default: 0,
validate(value) {
if(value \< 0) {
throw new Error('Age Must be a Postive number')
}
}
},
tokens: \[{
token: {
type: String,
required: true
}
}\],
avatar:{type: String}
}, {
timestamps: true
})
app.post('/users/me/avatar', authCheck, upload.array('avatar\[\]', 10), async (req,res,next)=\>{
console.log(req.file)
// const buffer = await shrap(req.file.path).resize({width:250,height:250}).png().toFile(req.file.destination, 'resized');
req.user.avatar = req.files.path,
await req.user.save()
res.status(200).send()
}, (error, req,res,next) =\>{
res.status(400).send({
error: error.message
})
})
I am try to upload images on server and save image path in mongoDb database. but image path not stored in database

Related

How to define a proper mongoose schema?

Is this a proper way to define it?
const mongoose = require("../database");
// create a schema
var userschema =new mongoose.Schema({
name: String,
password: String,
email:String
});
var userModel=mongoose.model('users',userSchema);
module.exports = mongoose.model("Users", userModel);
//Please Try In This Way
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const User = mongoose.Schema(
{
name: {
type: String,
default: "",
trim: true,
},
email: {
type: String,
default: "",
trim: true,
validate: {
validator: async function (email) {
const user = await this.constructor.findOne({ email });
if (user) {
if (this.id === user.id) {
return true;
}
return false;
}
return true;
},
message: (props) => "This email is already in use",
},
required: [true, "User email required"],
},
password: {
type: String,
default: "",
trim: true,
select: false,
},
mobile: {
type: String,
default: "",
trim: true,
},
experience: {
type: String,
default: "",
trim: true,
},
agree: {
type: Array,
default: "",
trim: true,
},
status: {
type: Number,
default: 1,
},
type: {
type: String,
},
isDelete: {
type: Boolean,
default: false,
},
},
{
timestamps: { createdAt: "createdAt", updatedAt: "updatedAt" },
}
);
module.exports = mongoose.model("User", User);

Mongoose error with PUT request but not with POST or GET

I have a schema that looks like:
const houseSchema = new mongoose.Schema({
address: {
type: String,
required: true,
trim: true,
},
city: {
type: String,
required: true,
},
roofType: {
type: String,
//required: true,
},
repairType: {
type: String,
//required: true,
},
numFloors: {
type: Number,
//required: true,
},
isOwner: {
type: Boolean,
//required: true,
},
isGated: {
type: Boolean
},
includeFlat: {
type: Boolean
},
addedBy: [
{
name:{
type: String
},
time:{
type: String
},
}
],
});
const customerSchema = new mongoose.Schema({
firstName: {
type: String,
required: true,
trim: true,
},
lastName: {
type: String,
required: true,
trim: true,
},
phoneNumber: {
type: String,
required: true,
},
email: {
type: String,
},
//array of houseSchema objects
properties: [
houseSchema
],
});
And my endpoint that is used to update one of the 'properties' is:
router.route('/property').post(async (req,res) => {
const body = req.body;
Customer.updateOne({_id: req.query.id, properties: {$elemMatch: {_id: req.query.pId}}},
{
$set: {
"properties.$.address": body.address,
"properties.$.city": body.city,
"properties.$.roofType": body.roofType,
"properties.$.repairType": body.repairType,
"properties.$.numFloors": body.numFloors,
"properties.$.isOwner": body.isOwner,
"properties.$.isGated": body.isGated,
"properties.$.includeFlat": body.includeFlat
}
},
function(err){
if(err){
res.status(400).json('Error: ' + err);
}
else{
res.json('Property Updated!');
}
}
)
});
The endpoint works mostly fine (it returns the customer and all properties when i only search for and want to modify one of the 'properties') but only when it is a post or a get request and when it is a put request, the error says
Error: ValidationError: firstName: Path firstName is required., lastName: Path lastName is required., phoneNumber: Path phoneNumber is required.
I dont know if its a big deal or not, but I do not know why this is happening and would like to know. Just to be clear, the goal of this endpoint is to find one of the properties and update its values, not to change anything about a customer or any of their other properties.

How to solve MongoError: E11000 duplicate key error collection

I am Working in a MERN application. In one of my model of express.js I have student schema like below which have unique fields
Fullname: {
type: String,
required: true,
trim: true,
},
AdmissionNumber: {
type: String,
required: true,
trim: true,
maxlength: 10,
unique: true,
},
RollNumber: {
type: Number,
required: true,
trim: true,
maxlength: 4,
},
Age: {
type: Number,
required: true,
maxlength: 2,
},
Email: {
type: String,
trim: true,
required: true,
unique: true,
},
Faculty: {
type: ObjectId,
ref: "Faculty",
required: true,
},
pass: {
type: Number,
default: 0,
}
I am saving the student with the help of form like this
exports.addStudent = (req, res) => {
let form = new formidable.IncomingForm();
form.keepExtensions = true;
form.parse(req, (err, fields) => {
if (err) {
res.status(400).json({
error: "problem with feilds",
});
}
// destructuring feilds
const {
Fullname,
AdmissionNumber,
RollNumber,
Age,
Email,
Faculty,
} = fields;
if (
!Fullname ||
!AdmissionNumber ||
!RollNumber ||
!Age ||
!Email ||
!Faculty
) {
return res.status(400).json({
error: "Please fill all fields",
});
}
// TODO: restriction on fields
let student = new Student(fields);
student.save((err, student) => {
if (err) {
res.status(400).json({
error: "Saving Student in DB failed",
});
console.log(err);
}
res.json(student);
// console.log(student.gender);
});
});
};
When I try to add student it will be added only first time after that it showing an error
I have checked my DB collection there is only one field in the database.
I had this problem before and the solution that worked for me is to delete the collection from the database then try again

MongoDB gives duplicated error when I use the same name that is unique: false

I try to save and update an entry with upsert, checking the unicity (is that the word? uniqueness?), of my own id key, called id. However, when I create a new entry, with a new id, if I write the same name for the object, the error happens:
errmsg: 'E11000 duplicate key error collection:
app.ticket index: nombre_1 dup key: { nombre: "James
Bond" }', [Symbol(mongoErrorContextSymbol)]: {}
The controller looks like this:
exports.guardarParte = (req,res,next) =>{
const newParte = {
id: req.body.id,
nombre: req.body.nombre,
telefono: req.body.telefono,
ref: req.body.ref,
marca: req.body.marca,
fecha: req.body.fecha,
averia: req.body.averia
}
parte.updateOne({id:newParte.id},{$set:newParte}, {upsert:true}, (err,parte)=>{
if(err && err.code === 11000){
return res.status(409).send("El parte ya existe(?)"+err);
}
if(err){
return res.status(500).send("No se ha podido crear el parte");
}
res.send(parte);
})
}
The model looks like this:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
mongoose.set('useCreateIndex',true);
mongoose.set('useUnifiedTopology',true);
const reparacionSchema = new Schema({
id: {
type: String,
required: false,
trim: true,
unique: true
},
nombre: {
type: String,
required: false,
trim: true,
unique: false
},
telefono: {
type: Number,
required: false,
trim: false
},
ref: {
type: String,
required: false,
trim: false
},
marca: {
type: String,
required: false,
trim: false
},
fecha: {
type: Date,
required: false,
trim: false
},
averia: {
type: String,
required: false,
trim: false
},
},{
timestamps: true
});
module.exports = reparacionSchema;
As you see in the model, nombre is set as unique:false. knowing this, I don't get why the error.

Mongoose Populate not returning related data

I have the following Models:
const mongoose = require('mongoose');
mongoose.Promise = global.Promise;
const imputerSchema = new mongoose.Schema({
dninie: {
type: String,
trim: true,
},
name: {
type: String,
trim: true,
required: true,
},
lastname: {
type: String,
trim: true,
required: true,
},
second_lastname: {
type: String,
trim: true,
},
phone : {
type: Number,
unique: true,
trim: true,
},
qr: {
type : String,
unique: true,
default: Date.now
}
});
module.exports = mongoose.model('Imputer', imputerSchema)
const mongoose = require('mongoose');
mongoose.Promise = global.Promise;
const imputationSchema = new mongoose.Schema({
qr: {
type: String,
trim: true,
required: true,
ref: 'Imputer',
},
imputation_date: {
type: String,
default: Date.now,
required: true,
},
coordinates: {
type: [Number, Number],
index: '2d',
},
});
module.exports = mongoose.model('Imputation', imputationSchema);
and I trying to make a query like this:
Imputation.find()
.populate('imputer.qr')
.exec()
.then(docs => console.log(docs));
I also try
Imputation.find()
.populate('imputer')
.exec()
.then(docs => console.log(docs));
But I'm only got the documents on the imputation model without the field on the imputers model.
Here are some screenshots of how the documents look
Change your imputationSchema as follows:
const imputationSchema = new mongoose.Schema({
qr: {
type: mongoose.Types.ObjectId, ref: "Imputer",
trim: true,
required: true,
},
// other fields...
});
and then query like this:
Imputation.find()
.populate('qr')
.exec()
.then(docs => console.log(docs));