I'm trying to send a JSON object inside one of the fields I have, in order to store it in the MongoDB (Using Mongoose Schema). Right now I'm facing a server-sided JSON parsing error.
This is what I'm trying to send
{
"text":"N1y",
"localId":"123",
"type": "media",
"attachments": {
url:"Test.jpg",
publicId:"123"
}
}
My Moongose Schema
const messageSchema = mongoose.Schema({
createdAt: {
type: String,
default: new Date()
},
chatId: {
type: String,
required: true
},
localId: {
type: String,
required: true
},
text: {
type: String,
required: true
},
authorId: {
type: String,
required: true
},
type: {
type: String,
default: 'text'
},
attachments: {},
style: {
type: String,
default: 'normal'
}
Using Node.JS with Express.
In the schema update attachments type to object and request object in not correct json.
{
"text": "N1y",
"localId": "123",
"type": "media",
"attachments": {
"url": "Test.jpg",
"publicId": "123"
}
}
Schema
attachments: {
type : Object
},
OR
attachments: {
url: {
type: String
},
publicId: {
type: String
},
}
Related
I have a mongoDb model defined as follows:-
var mongoose = require("mongoose");
const postModel = new mongoose.Schema({
postId: {
type: String,
unique: true,
required: true
},
authorId: {
type: String,
required: true
},
post: {
authorHandle: {
type: String,
required: true
},
heading: {
type: String,
required: true
},
message: {
type: String,
required: true
},
creationDate: {
type: Date,
required: true
},
image: { type: Array },
video: { type: Array },
comments: {
type: Array
}
}
});
module.exports = mongoose.model("postModel", postModel);
Now I have a sample value of a document of the above model, suppose:-
postId: "aaa",
authorId: "bbb",
post: {
authorHandle: "someone#123",
heading: "hello",
message: "post 1",
creationDate: "some creation date string(please ignore this is irrelevant to my question)",
image: [],
video: [],
comments: [
{ commentId: "1", message: "Something", createdAt: sometime },
{ commentId: "2", message: "Something else", createdAt: sometime2 },
{ commentId: "3", message: "Something other", createdAt: sometime3 },
]
}
Now say the user wants to update the comment with commentId 2 of this post with postId "aaa". My question is that what is the best way to use the findOneAndUpdate() method to solve this problem?
const PostModel = require("./models/PostModel"); //just importing the model that is defined above
//the below is happening inside a request handler in Node + Express
PostModel.findOneAndUpdate(
//what to do here
)
What I have tried is pulling out that whole object and replacing it with a new object with the new message. But that doesnt seem like a very efficient way. Any and all help is greatly appreciated!
You should write:
const updatedPost = await PostModel.findOneAndUpdate(
{ postId: 'aaa', 'post.comments.commentId': 2 },
{ 'post.comments.$.message': 'Updated message'},
{ new: true }
)
I try to create new collection with mongodb.
I wrote the MongoDB shcema, Nodejs+express code and everything work fine until I send parameters with Json inside them.
I was created this schema (and also more code under this schema) but its not work and I got error:
const partySchema = mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
title: { type: String, required: true },
datetime: { type: Date, required: true },
location: {
scraping_location: { type: String, required: true },
display_location: { type: String, required: false },
city: { type: String, required: false },
adress: { type: String, required: false },
area: { type: String, required: false }
},
picture: { type: String, required: true },
url: { type: String, required: true },
affiliate_url: { type: String, required: true },
music_by: {type: [], required: false },
music_type: {type: [], required: false },
min_age_for_men: {type: Number, required: true },
min_age_for_women: {type: Number, required: true },
status_check: {type: Boolean, default: false },
tags: {
concept: { type: String, required: false },
free_text: { type: [], required: false }
},
producer_id: { type: String, required: false },
});
and the code that I wrote with nodejs+express is this:
const { title, datetime, location, picture, url, affiliate_url, music_by, music_type, min_age_for_men, min_age_for_women, tags, producer_id } = req.body;
const party = new Party({
_id: new mongoose.Types.ObjectId(),
title,
datetime,
location: { scarping_location: location.location_scarping },
picture,
url,
affiliate_url,
music_by,
music_type,
min_age_for_men,
min_age_for_women,
tags,
producer_id
});
party.save().then(() => {
res.status(200).json({
message: 'Create a new user'
})
}).catch(error => {
res.status(500).json({
error
})
});
when I send reqeust to the api with this body:
{
"title": "test",
"datetime": "2002-07-15T10:00:00+0300",
"location": {
"location_scarping": "new york"
},
"picture": "test.jpg",
"url": "https://google.com",
"affiliate_url": "https://google.com",
"min_age_for_men": 18,
"min_age_for_women": 16
}
I got this error:
{
"error": {
"errors": {
"location.scraping_location": {
"name": "ValidatorError",
"message": "Path `location.scraping_location` is required.",
"properties": {
"message": "Path `location.scraping_location` is required.",
"type": "required",
"path": "location.scraping_location"
},
"kind": "required",
"path": "location.scraping_location"
}
},
"_message": "Party validation failed",
"name": "ValidationError",
"message": "Party validation failed: location.scraping_location: Path `location.scraping_location` is required."
}
}
why its happend?
Looks like this is just a typo, from your schema:
scraping_location: { type: String, required: true }
You're trying to insert: location_scarping not location_scraping
"location_scarping": "new york"
Hopefully that fixes it.
I have model
username: {
type: String,
required: true,
},
firstname: {
type: String,
},
lastname: {
type: String,
},
email: {
type: String,
required: true,
},
comments: [
{
name: {
type: String,
},
text: {
type: String,
},
},
],
And I want update userModel using Controllers this.router.patch(${this.path}/:id, this.editProfile);
const user = await userModel.findByIdAndUpdate(
req.params.id,
{
...req.body,
},
{ new: true, runValidators: true },
);
return res
.status(StatusCodes.OK).send(user)
Everything works but the problem is when I update comments:
When I sent req "comments": [
{
"name": "coment",
"text":"text"
}
]
It's okay, but when I update without name
{
"text":"text2"
}
the name disappears, but I want that text2 was updated, and the name still exists. What I should use?
I am following Brad Traversy's MERN stack development course and In 4th section, I can't make post request to route localhost:5000/api/profile,
after sending post request with data as handle,status,skills which are fields in my collection, it returns error skills field required.
skills is array of strings sent from user-input.
when I checked collection-profile is created or not then it's not created and only one collection is shown as main collection user,
I followed each line of code in tutorial but getting error, I wanted to get Profile collection to be created at remote mlab mongodb,
my profile model code is
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
// Create Schema
const ProfileSchema = new Schema({
user: {
type: Schema.Types.ObjectId,
ref: "users"
},
handle: {
type: String,
required: true,
max: 40
},
company: {
type: String
},
website: {
type: String
},
location: {
type: String
},
status: {
type: String,
required: true
},
skills: {
type: [String],
required: true
},
bio: {
type: String
},
githubusername: {
type: String
},
experience: [
{
title: {
type: String,
required: true
},
company: {
type: String,
required: true
},
location: {
type: String
},
from: {
type: Date,
required: true
},
to: {
type: Date
},
current: {
type: Boolean,
default: false
},
description: {
type: String
}
}
],
education: [
{
school: {
type: String,
required: true
},
degree: {
type: String,
required: true
},
fieldofstudy: {
type: String,
required: true
},
from: {
type: Date,
required: true
},
to: {
type: Date
},
current: {
type: Boolean,
default: false
},
description: {
type: String
}
}
],
social: {
youtube: {
type: String
},
twitter: {
type: String
},
facebook: {
type: String
},
linkedin: {
type: String
},
instagram: {
type: String
}
},
date: {
type: Date,
default: Date.now
}
});
module.exports = Profile = mongoose.model("profile", ProfileSchema);
using validator.js module, I am validating input-fields,
if (Validator.isEmpty(data.skills)) {
errors.skills = "Skills field is required";
}
so, I can't find why exactly I can't find new collection as profile?
I tried using mongodb-locally, but it didn't help.
my Github repo link.
I returned user's details when route /api/users/current and changed response on success
before changing:
res.json({ msg: "Success" });
after:
passport.authenticate("jwt", { session: false }),
(req, res) => {
res.json({
id: req.user.id,
name: req.user.name,
email: req.user.email
});
}
);
Here is my commit history,
then It didn't give error as skills field is required,
I have this data structure. I would like to push a new sibling into a specific members sibling array:
const FamilySchema = mongoose.Schema({
username: { type: String, required: true },
family_name: { type: String, required: true },
password: { type: String, required: true },
members: [
{
fname: { type: String, required: true },
lname: { type: String, required: true },
mname: { type: String },
birth_date: { type: String },
birth_town: { type: String },
birth_state: { type: String },
death_date: { type: String },
death_town: { type: String },
death_state: { type: String },
short_bio: { type: String },
long_bio: {type: String },
parents: [
{
parent_id: { type: String, required: true }
}
],
siblings: [
{
sibling_id: { type: String, required: true }
}
],
children: [
{
children_id: { type: String, required: true }
}
],
pictures: [
{
url: { type: String, required: true }
}
],
}
]
});
I want to push a new sibling into the sibling array for a SPECIFIC member in the larger family document. I'm trying to do it like this, and it's not working.
Family
.update(
{
_id: FAMILY_ID,
"members._id" : MEMBER_ID
},
{
$push : {
"members.$.siblings" : {
"sibling_id": THE_VALUE_I_WANT_ADDED
}
}
}
);
Any thoughts? My Mongoose knowledge is failing me.