Pushing Array of object from react to mongodb+express server issue - reactjs

I'm store array of object but it is giving mer following error.
(node:87929) UnhandledPromiseRejectionWarning: ValidationError: Place validation failed: placesToVisit: Cast to embedded failed for value "[{"name":"xczc","location":"zczxc","description":"czxczx"}]" (type string) at path "placesToVisit" because of "ObjectParameterError"
here is my schema:
placesToVisit: [
{
name: {
type: String,
required: [true, "Please enter the place's name"],
},
description:{
type: String,
required: [true, "Please enter the place's description"],
},
location:{
type: String,
required: [true, "Please enter the place's location"],
}
},
],
here is my contoller:
exports.createPlace = async (req, res) => {
try {
const newPlace = await new Place({
placesToVisit:req.body.placesToVisit,
});
newPlace.save()
debugger
res.status(201).json({
success:true,
message:"Place Created Successfully",
newPlace
})
} catch (error) {
return res.status(500).json({
success:false,
error:error.message
})
}
};
here is my formdata structure:
data.append("placesToVisit",JSON.stringify(values.placesToVisit))
here is ss of yaload

You must convert the string to an array:
placesToVisit: JSON.parse(req.body.placesToVisit),

Related

how to insert checkbox as array into mongodb

I don't know why it's not being inserted. it doesn't show an error or anything so i couldn't figure out the problem.
the tags [ '61c2102d165a5af742091a70', '61c37621165a5af742093a1a' ].
here is my insert function:
insert: async(req,res)=> {
const {userid,tags}=req.body;
console.log("userid", userid)
console.log("tags", tags) //tag [ '61c2102d165a5af742091a70', '61c37621165a5af742093a1a' ]
try {
User.findByIdAndUpdate(
userid,
{ $push: { tags: {$each : tags } }} ,
);
return res.status(200).send({msg:"success"});
} catch (error) {
console.log(error);
res.status(500).send({ msg: "Something went wrong" });
}
}
my user schema:
tags: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'Tag'
}]
tag schema:
const TagSchema = new Schema({
name: {
type: String
},
type: {
type: Object,
},
timestamp: {
type: Date,
default: Date.now
},
});
Most codes i saw do it like that but i couldn't figure out why mine isn't working
Since you are using async, you can make use of await to see it if is saved or not. Rewriting logic in this way you can catch saved instance and return success or failure.
insert: async(req,res)=> {
const {userid,tags}=req.body;
console.log("userid", userid)
console.log("tags", tags) //tag [ '61c2102d165a5af742091a70', '61c37621165a5af742093a1a' ]
const doc = await User.findByIdAndUpdate(
userid,
{ $push: { tags: {$each : tags } }} ,{new:true}
);
if (!doc) return res.status(500).send({ msg: "Something went wrong" });
return res.status(200).send({msg:"success"});
}

Mongoose: TypeError: Invalid value for schema path `guildId.type`, got value "undefined"

I got this error but I don't know what I have done wrong.
My code:
const mongoose = require('mongoose');
const GuildConfigSchema = new mongoose.Schema({
guildId: {
type: mongoose.SchemaType.String,
required: true,
unique: true,
},
prefix: {
type: mongoose.SchemaType.String,
required: true,
default: 'b!',
},
defaultRole: {
type: mongoose.SchemaType.String,
required: false,
},
memberLogChannel: {
type: mongoose.SchemaType.String,
required: false,
},
});
module.exports = mongoose.model('GuildConfig', GuildConfigSchema);
And my guild create event where I am setting the values of the database:
// https://discord.js.org/#/docs/main/stable/class/Client?scrollTo=e-guildCreate
const BaseEvent = require('../utils/structures/BaseEvent');
const GuildConfig = require('../database/schemas/GuildConfig');
module.exports = class GuildCreateEvent extends BaseEvent {
constructor() {
super('guildCreate');
}
async run(client, guild) {
try {
const guildConfig = await GuildConfig.create({
guildId: guild.id,
});
console.log('Successfully joined server!');
} catch(err) {
console.log(err);
}
}
}
My error:
TypeError: Invalid value for schema path `guildId.type`, got value "undefined"
Does anyone see what I've done wrong?
explicitly export GuildConfigSchema
module.exports.GuildConfigSchema = GuildConfigSchema;
and use destructuring where the schema is required.
const { GuildConfigSchema } = require("path to schema file");

CastError: Cast to ObjectId failed for value "{ _id: ':5ec5cc919efcf581eb692690' }" at path "_id" for model "Posts"

Checking the router on the server side it console logs the right values, only the follow error is popping up in here. Trying to build a counter that should update the value on the backend. But the problem I have is that value will not be stored in there. When using Postman the value will be stored successfully. What is the solution that can fix this issue.
export const incrementProduct = (index, updateAmount, id) => {
return dispatch => {
dispatch(increment(index));
try {
axios.patch(`${API_URL}/:${id}`, {
amount: updateAmount
}).then(res => {
console.log(res.config);
})
} catch(err) {
console.log(err)
}
}
}
const PostSchema = mongoose.Schema({
title: {
type: String,
required: true
},
description: {
type: String,
required: true
},
amount: {
type: Number,
required: true
},
editable: {
type: Boolean,
required: true
},
data: {
type: Date,
default: Date.now
}
});
// update
router.patch('/:postId', async(req, res) => {
console.log('update', req.params.postId + 'amount ' + req.body.amount)
try {
const updatedPost = await Post.findByIdAndUpdate(
{_id: req.params.postId}, <--- this cause the console error...
{$set:
{
amount: req.body.amount
},
})
console.log('try')
res.json(updatedPost)
} catch(err) {
console.log(err + 'test ')
res.json({ message: err })
}
})
You need to remove : in the patch url like this:
axios.patch(`${API_URL}/${id}`
Also findByIdAndUpdate requires only the value of _id, so you can only pass the value like this:
await Post.findByIdAndUpdate(req.params.postId, ...
findByIdAndUpdate(id, ...) is equivalent to findOneAndUpdate({ _id: id }, ...).

AngularJS Mongoose findOne OK but save error :DocumentNotFoundError:

On client.save() below, I have the following error (which is catch properly):
DocumentNotFoundError: No document found for query "{ _id: '5bfbce595be7d1047c976e6b' }"
app.put('/api/client', function (req, res) {
Client.findOne(new mongoose.Types.ObjectId(req.body._id)).then(client => {
//This is OK, I can see client and its properties
client.name = req.body.name;
//This is OK, I can see the updated client and its properties
client.save().then(test => {
console.log("ERR=" + err);
console.log(test);
}).catch(err => console.log("ERR :" + err));
res.json(client);
});
});
The model is as such:
mongoose.model('Client', {
_id: {type: String, default: ''},
name: {type: String, default: ''},
creationDate: {type: Date, default: ''}
});
How come the document is found on FindOne() and no more on save()?
try to do so:
mongoose.model('Client', {
_id: { type: mongoose.Schema.Types.ObjectId, auto: true },
name: { type: String, default: '' },
creationDate: { type: Date, default: Date.now() }
});
And
Client.findOne().where({_id : req.body._id})...

How to post an array of ObjectId references to an existing collection in node js

I am new to Mongodb and nodejs. My questions is with respect to performing an post operation on collection in mongodb that stores ObjectId references to another collection.
Exact Scenario being:
I have set of registered users in the Users document. Similarly, I have set of roles available in the Roles document.
Now, what I am trying to do is post the user with the roles from the Roles document. A user could have multiple roles and hence I want to store all the ObjectId references to the Roles in Users document.
I have the following definition for the Users and Roles document.
var roleSchema = new mongoose.Schema({
roleId: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Roles'
}
});
const userSchema = new mongoose.Schema({
Username: {
type: String,
required: true,
minlength: 5,
maxlength: 255,
unique: true
},
FirstName: {
type: String
},
LastName: {
type: String
},
Email: {
type: String,
required: true,
minlength: 5,
maxlength: 255
},
Password: {
type: String,
required: true,
minlength: 5,
maxlength: 1024
},
Roles: [roleSchema],
Active: {type: Boolean, default: true},
SuperUser: {type: Boolean, default: false}
},{
timestamps: true
});
const rolesSchema = new mongoose.Schema({
RoleName: {
type: String,
required: true,
minlength: 5,
maxlength: 255,
unique: true
},
Description: {
type: String
},
Active: {type: Boolean, default: true}
}, {
timestamps: true
});
router.post('/', [auth, admin], async (req, res) => {
const { error } = validate(req.body);
if (error) return res.status(400).send(error.details[0].message);
let user = await User.findOne({ Username: req.body.Username });
if (user) return res.status(400).send('User with username: ', req.body.Username, 'already exists. Please try with any other username');
// Begin: Code added to populate Roles in Users document. Look up the roles information in req.body payload
let rolesArray = {};
if(req.body.Roles !== null) {
req.body.Roles.forEach(element => {
objectId = mongoose.Types.ObjectId(element);
const roleInfo = Roles.findById(objectId);
if (!roleInfo) return res.status(400).send('Invalid Role in Input.');
});
}
console.log('Roles : ', rolesArray);
user = new User(_.pick(req.body, ['Username', 'FirstName', 'LastName' ,'Email', 'Password', 'Active','SuperUser', 'Roles']));
rolesArray.forEach(role => {
console.log('Role in user : ', role);
user.Roles.push = role;
});
// End: Code added to populate Roles in Users document. Look up the roles information in req.body payload
const salt = await bcrypt.genSalt(10);
user.Password = await bcrypt.hash(user.Password, salt);
await user.save();
const token = user.generateAuthToken();
res.header('x-auth-token', token).send(_.pick(user, ['_id', 'FirstName', 'LastName' ,'Email', 'Roles']));
});
I have attached the code for the POST operation but even that is not working.
I can work on the PUT operation if the POST operation is successful.
Despite all my trials, I am not able to understand how to loop through the req.body.Roles to set the ObjectIds in the Users document.
Also, while performing the GET operation, I would like to have the Role Name as well as the RoleID retrieved in response when I query the Users document.
Thanks.

Resources