Hi every one please can someone help me to update user that receive image and updated it then render the user with the image to frontend.i get stuck I search by google but I didn't find what I search for,there's my code :
this is the userModel:
import mongoose from "mongoose";
const userSchema = new mongoose.Schema({
name: {type: String, required: true},
fname: {type: String, required: true},
phone: {type: String, required: true},
email: {type: String, required: true, unique: true},
password: {type: String, required: false},
image: {type: {name: String, img: {contentType: String, data: Buffer}}, required: false},
isAdmin: {type: Boolean, default: false, required: true},
}, {
timeStamps: true
});
const User = mongoose.model("User", userSchema);
export defau
userRouter.post("/upload/:id", async(req, res)=> {
upload.single("productImage")
const updatedUser = User.findByIdAndUpdate(req.params.id,{$set: {image: {name: req.files.productImage.name, img: {contentType: req.files.productImage.mimetype, data: fs.createReadStream(path.join(__dirname, '../../frontend/public/images'))}}}
})
res.send("ok");
console.log(updatedUser)
})
You have to add option {new: true}, so that the document returned has the last updated data, and also send the http response in the callback of the update operation
userRouter.post('/upload/:id', async (req, res) => {
upload.single('productImage');
const updatedUser = User.findByIdAndUpdate(
req.params.id,
{
$set: {
image: {
name: req.files.productImage.name,
img: {
contentType: req.files.productImage.mimetype,
data: fs.createReadStream(
path.join(__dirname, '../../../frontend/public/images')
),
},
},
},
},
{ new: true },
(err, doc) => {
if (err) return res.send(err);
res.send(doc);
}
);
});
Related
How can I get and populate the id ref to the order? I grab the id of the product and user. Then when I use my get method, I will get all the details of the products and users.
For example, my data will show all information
Product
a. title
b. price
c. productImage
User
a. username
b. studentId
I tried to use populate, but I think I'm doing it wrong.
export const getOrders = async (req,res) =>{
try {
const order = await Order.findOne({productId: '634e91d256326381d5716993'})
.populate()
.exec()
res.status(400).json(order)
} catch (error) {
res.status(404).json({message: error.message})
}
}
OrderSchema
const OrderSchema = mongoose.Schema({
productId: {type: mongoose.Schema.Types.ObjectId, ref: 'Product', required: true},
buyerId: {type: mongoose.Schema.Types.ObjectId, required: true, ref: 'User'},
sellerId: {type: mongoose.Schema.Types.ObjectId, required: true, ref: 'User'}
})
export default mongoose.model('Order', OrderSchema)
ProductSchema
const ProductSchema = mongoose.Schema({
user_id: {type: mongoose.Schema.Types.ObjectId, required: true, ref: 'User'},
title: {type: String},
description: {type: String},
categories: {type: Array},
price: {type: Number},
productImage: {type: String}
},
{ timestamps: { createdAt: true } }
)
export default mongoose.model('Product', ProductSchema)
UserSchema
const UserSchema = mongoose.Schema({
username: {type: String, unique: true, required: true},
password: {type: String, required: true},
email: {type: String, unique: true, required: true},
studentid: {type: String, unique: true, required: true},
isAdmin:{type: Boolean, default: false},
},
{ timestamps: { createdAt: true } }
)
export default mongoose.model('User', UserSchema)
You have to specify what you want to populate inside the .populate() method:
await Order.findOne({productId: '634e91d256326381d5716993'})
.populate([
{ path: 'productId', select: 'title price productImage' },
{ path: 'buyerId', select: 'username studentid' }
])
.exec()
My lines are empty.
My scheme:
// models/Tobacco.js
const mongoose = require('mongoose');
// FYI: important for populate work!!!
const tobaccoLineSchema = mongoose.Schema({
name: {type: String, required: true},
subTitle: {type: String, required: true},
count: {type: Number, required: true}
});
const Schema = mongoose.Schema;
const TobaccoSchema = new mongoose.Schema({
createdAt: {
type: Date,
default: Date.now
},
title: {
type: String,
required: true
},
subTitle: {
type: String,
required: false
},
bannerSrc: {
type: String,
required: false
},
socials: [],
lines: [
{
type: Schema.Types.ObjectId,
ref: 'tobaccoLine'
}
]
}
,{toObject:{virtuals:true}, toJSON:{virtuals:true}});
const TobaccoLine = mongoose.model('tobaccoLine', tobaccoLineSchema);
module.exports = mongoose.model('tobacco', TobaccoSchema);
Added populate line in API
router.get('/:id', (req, res) => {
Tobacco.findById(req.params.id).populate('lines')
.then(tobacco => res.json(tobacco))
.catch(err => res.status(404).json({ notobaccofound: 'No Tobacco found' }));
});
Database:
How I can't see issues. Client side fetches tobaccos but lines are empty.
Need to add back property into the child entity scheme.
const tobaccoLineSchema = mongoose.Schema({
name: {type: String, required: true},
subTitle: {type: String, required: true},
count: {type: Number, required: true},
_tobacco: { type: Schema.Types.ObjectId,
ref: 'tobacco' }
});
This is my existing schema,
const mongoose = require('mongoose');
const position = mongoose.Schema({
startIndex: { type: Number, required: true },
endIndex: { type: Number, required: false },
});
const Column = mongoose.Schema({
name: { type: String, required: true },
type: { type: String, enum: ["Description","ID","Time"], required: true },
positions: [position],
dataType: { type: String, enum: ["int", "float", "Double","String"], required: true },
oldName: {type:String, required: false }
});
const enrichedEventSchema = mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
projectId: { type: mongoose.Schema.Types.ObjectId, ref: 'Project', required: true },
name: { type: String, required: true,unique: true },
DataSourceID: { type: String, required: false},
delimiter: { type: String, required: true },
format: {type:String, enum:["JSON","DELIMITED","FixedWidth","LOG"], required: true},
columns:[Column]
});
module.exports = mongoose.model('EnrichedEvent', enrichedEventSchema);
Api for Post route:
router.post("/:projectId/events/enriched", (req, res, next) => {
const enrichedEvent = new EnrichedEvent({
_id: mongoose.Types.ObjectId(),
name: req.body.name,
projectId: req.params.projectId, //taking from url
delimiter: req.body.delimiter,
format: req.body.format,
columns:req.body.columns,
});
return enrichedEvent.save()
.then(result => {
res.status(201).json({
message: "Event stored",
createdEvent: {
_id: result._id,
projectId: result.projectId,
name: result.name,
type: result.type,
delimiter: result.delimiter,
columns:result.columns,
format:result.format
}
});
})
.catch(err => {
console.log(err);
res.status(500).json({
error: err
});
});
});
well my requirement is that
All EnrichedEvents Should have at least 2 Columns defined one with
Type = ID,
Type = TIME.
if FORMAT = DELIMITED then data must have Delimiter Field; ALL Columns should have a mandatory Starting Index.
if FORMAT = FIXEDWIDTH then data must have all Columns should have mandatory Starting and Ending Index.
all i could come up with is using if condition, something like this.
if ( req.body.format == 'DELIMITED' )
{
//then how to use my schema in my code??
}
I m stuck in this for 3 days, not getting logic. Any help would be appreciated.
Try making two different schemes.
const positionDel = mongoose.Schema({
startIndex: { type: Number, required: true },
endIndex: { type: Number, required: false },
});
const positionFixed = mongoose.Schema({
startIndex: { type: Number, required: true },
endIndex: { type: Number, required: true},
});
router.post("/:projectId/events/enriched", (req, res, next) => {
const enrichedEvent = new EnrichedEvent({
_id: mongoose.Types.ObjectId(),
name: req.body.name,
projectId: req.params.projectId, //taking from url
delimiter: req.body.delimiter,
format: req.body.format,
columns:req.body.columns,
});
if(delimiter=='DELIMITED'){
return enrichedEvent_SchemaForDELIMITED.save()
.then(result=>{
//use the result.
})
.catch(err=>{
// error thrown
})
}
else if(delimiter=="FIXEDWIDTH"){
return enrichedEvent_SchemaForFIXED.save()
.then(result=>{
//use the result.
})
.catch(err=>{
// error thrown
})
}
});
Look at the code. The logic will be like this.
I am a begginer using nodeJs, mongoose and MongoDB and i ran into a problem that after several hours of research i cannot solve. I'll try to explain clearly.
First things first, so i'll briefly explain the logic. I have Users that can have several Items, so in each user i want to have an array of objectId's that identify the items they have.
I have User.js and userService.js files, as well as Item.js and itemService.js files.
My User.js file is as follows:
const restful = require('node-restful')
const mongoose = restful.mongoose
const validator = require('validator')
var Schema = mongoose.Schema
const utilizadorSchema = new mongoose.Schema({
username: { type: String, default: '', required: true, unique: true},
email: { type: String, default: '', required: true, unique: true, validate: [validator.isEmail, 'Invalid email']},
password: { type: String, default: '', required: true},
equipaID: [{
type: Schema.Types.ObjectId, ref: 'Equipa'}],
itens: [{
type: Schema.Types.ObjectId, ref: 'Item'}],
poderDeAtaque: { type: Number, default: 10},
poderDeDefesa: { type: Number, default: 10},
healthPoints: { type: Number, default: 100},
classificacaoDuelos: { type: Number, default: 0},
vitorias: { type: Number, default: 0},
derrotas: { type: Number, default: 0},
validado: { type: Boolean, default: false}
})
module.exports = restful.model('Utilizador', utilizadorSchema, 'Utilizadores')
Now, my userService.js file:
const Utilizador = require('./utilizador')
var item = require('./item')
Utilizador.methods(['get', 'post', 'put', 'delete'])
Utilizador.update(
{_id: Utilizador._id},
{ $push: {itens: item._id}},
{ upsert: true}
)
module.exports = Utilizador
Item.js:
const restful = require('node-restful')
const mongoose = restful.mongoose
const itemSchema = new mongoose.Schema({
descricao: { type: String, required: true},
categoria: { type: String, required: true},
nivel: { type: Number, required: true},
poderDeAtaque: { type: Number, required: true},
poderDeDefesa: { type: Number, required: true},
healthPoints: { type: Number, required: true},
})
module.exports = restful.model('Item', itemSchema, 'Itens')
ItemService.js:
const Item = require('./item')
Item.methods(['get', 'post', 'put', 'delete'])
Item.updateOptions({new: true, runValidators: true})
module.exports = Item
So, my problem is this, i can successfully add an item to an user, however, when i try to add another item to the same user, it replaces the value in the array, instead of adding a new one. I've tried using $addToSet instead of $push, but to no success.
I have a schema
const RoomSchema = mongoose.Schema({
title: {
type: String,
required: true
},
body: {
type: String,
required: true
},
author: {
type: String,
required: true
},
resource: {
type: String
},
posts: {
type: Array,
default: []
},
url: {
type: String
},
created_at: {
type: String,
required: true
}});
Field 'posts' is another document in my db, defined by the following schema:
const PostSchema = mongoose.Schema({
header: {
type: String,
required: true
},
body: {
type: String,
required: true
},
author: {
username: {type:String, required: true},
_id: {type:String, required:true}
},
room: {
type: String,
required: true
}});
So, I'm trying to create a query that would update fields of certain post inside posts array inside room. I've already tried suggested here, thought without results. I would appreciate any help on the subject
Room.update({ '_id': roomId, 'posts._id': postId },
{ $set: { 'posts.$.header': newHeader, 'posts.$.body': newBody } },
callback);