mongoDb database form-data empty response - node.js

I am sending Rest POST Request(form-data) using postman to mongoDb. Even after providing all the key-value pairs in the Model, only the product _id gets stored into the database not other array of objects. Here's my model schema:
const mongoose = require('mongoose');
const productSchema = mongoose.Schema({
name: String,
price: Number,
editor1: String,
year: String,
quantity: Number,
subject: String,
newProduct: String,
relatedProduct: String,
//coverImage: { type: String, required: false }
});
module.exports = mongoose.model('Product', productSchema);
And here's my POST request for the products:
exports.products_create_product = (req, res, next) => {
const product = new Product(req.body);
product
.save()
.then(result => {
console.log(result);
res.status(201).json({
message: "Created product successfully",
createdProduct: {
name: result.name,
price: result.price,
_id: result._id,
request: {
type: "GET",
url: "http://localhost:3000/products/" + result._id
}
}
});
})
.catch(err => {
console.log(err);
res.status(500).json({
error: err
});
});
};
And this is my result output:
{
"message": "Created product successfully",
"createdProduct": {
"_id": "5b2df3420e8b7d1150f6f7f6",
"request": {
"type": "GET",
"url": "http://localhost:3000/products/5b2df3420e8b7d1150f6f7f6"
}
}
}
Tried every possible way to solve this but in vain.

try the callback
product.save((err,result) =>{
if(err){
res.status(500).json({
error: err
});
return false
}
res.status(201).json({
message: "Created product successfully",
createdProduct: {
name: result.name,
price: result.price,
_id: result._id,
request: {
type: "GET",
url: "http://localhost:3000/products/" + result._id
}
}
})

First let's try to understand why this happens ? ,
When you use .json() method inside this method it uses JSON.stringify() function what this function does is that take any JavaScript value and convert it to JSON string for example
let product = {
name : 'p1' ,
price : 200
}
console.log(JSON.stringify(product)); // {"name":"p1","price":200}
that's good , but you should know that if this function during the conversion see any undefined values it will be omitted ,
for example
let product = {
id:"23213214214214"
} // product doesn't have name property and its undefind
console.log(JSON.stringify({
id:product.id ,
name : product.name
})); // {"id":"23213214214214"}
if you look at the example above you'll see that because the value of name is **undefined ** you get a JSON output but only with the id value , and any value that is undefined will not be in the result .
that's the main reason why you get the result with only the product._id because other values like price and name are undefined .
so what to do to solve this problem ?
log the req.body and make sure that it has properties like name and price and I think this is the main reason of the problem because when you create the product variable it will only has the _id prop because other props are not exist .
after you create the product log it to the console and make sure that it has other properties like name and price

#mostafa yes I did tried.
{
"count": 3,
"products": [
{
"_id": "5b2e2d0cb70f5f0020e72cb6",
"request": {
"type": "GET",
"url": "https://aa-backend.herokuapp.com/products/5b2e2d0cb70f5f0020e72cb6"
}
},
{
"_id": "5b2e2d37b70f5f0020e72cb7",
"request": {
"type": "GET",
"url": "https://aa-backend.herokuapp.com/products/5b2e2d37b70f5f0020e72cb7"
}
},
{
this is the only output I am getting.

Related

mongoose findOneAndUpdate gives different user

I was trying to $pull an object inside my cart collections. but after I make a request and sent a specific _id it gives me a different person.
this was the _id I sent from my client side.
{ id: '62a849957410ef5849491b1b' } /// from console.log(req.params);
here's my mongoose query.
export const deleteItem = (req,res) => {
const { id } = req.params;
console.log(id);
try {
if(!mongoose.Types.ObjectId.isValid(id)) return res.status(404).json({ message: 'ID not found' });
ClientModels.findOneAndUpdate(id, {
$pull: {
cart: {
product_identifier: req.body.cart[0].product_identifier
}
}
},{
new: true
}).then(val => console.log(val)).catch(temp => console.log(temp));
} catch (error) {
res.status(404).json(error);
}
}
after the request here's the callback.
{
_id: new ObjectId("62a77ab16210bf1afd8bd0a9"),
fullname: 'Gino Dela Vega',
address: '008 Estrella.st santo cristo',
email: 'gamexgaming1997#gmail.com',
google_id: 'none',
birthday: '1997-12-30',
number: 9922325221,
gender: 'Male',
username: 'ginopogi',
password: '$2b$12$YCc1jclth.ux4diwpt7EXeqYyLOG0bEaF.wvl9hkqNVptY.1Jsuvi',
cart: [],
wishlist: [],
toBeDeliver: [],
Delivered: [],
__v: 0
}
as you guys can see after sending a specific _id to find a user...the callback gives me a different user reason that I can't pull the specific object inside cart. (the object I was trying to pull is on another user)
Probably because findOneAndUpdate expect a filter as first parameter, try to switch to findByIdAndUpdate if you want to filter by a specific _id:
export const deleteItem = (req, res) => {
...
ClientModels.findByIdAndUpdate(
id,
{
$pull: {
cart: {
product_identifier: req.body.cart[0].product_identifier,
},
},
},
{
new: true,
}
)
.then((val) => console.log(val))
.catch((temp) => console.log(temp));
} catch (error) {
res.status(404).json(error);
}
};

Mongoose and Postman: test a model with nested objects

I created a model like this in nodeJS, using Mongoose:
'use strict';
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var plantSchema = new Schema({
plantData: [
{
family: { type: String, default: 'Liliaceae' },
genusObj: {
genus: { type: String, required: 'Please enter the genus plant name' },
tulipGroup: { type: String }, // e.g. Single Early
tulipGroupNumber: { type: Number } // e.g. 1
},
species: { type: String, required: 'Please enter the species plant name' },
commonName: { type: String },
description: { type: String },
mainImage: {},
otherImages: {},
images: {},
}
],
detailsData: [ .... ]
});
module.exports = mongoose.model('plants', plantSchema);
And this is my controller:
var mongoose = require('mongoose'),
Plant = mongoose.model('plants');
// READ ALL
exports.list_all_plants = function(req, res) {
Plant.find({}, function(err, plants) {
if (err) {
res.send(err);
}
res.json(plants);
});
};
// CREATE
exports.create_new_plant = function(req, res) {
var new_plant = new Plant(req.body);
new_plant.save(function(err, plant_inserted) {
if (err) {
res.send(err);
}
res.json(plant_inserted);
});
};
// READ (probably plantId comes from an _id previously retrieved)
exports.read_a_plant = function(req, res) {
Plant.findById(req.params.plantId, function(err, plant_searched) {
if (err) {
res.send(err);
}
res.json(plant_searched);
});
};
// UPDATE
exports.update_a_plant = function(req, res) {
Plant.findOneAndUpdate(
{
_id: req.params.plantId
},
req.body,
{new: true},
function(err, plant_to_update) {
if (err) {
res.send(err);
}
res.json(plant_to_update);
}
);
};
// DELETE
exports.delete_a_plant = function(req, res) {
Task.remove(
{
_id: req.params.plantId
},
function(err, task) {
if (err) {
res.send(err);
}
res.json({ message: 'Plant successfully deleted' });
}
);
};
And finally, i have this router:
'use strict';
module.exports = function(app) {
var plantList = require('../controllers/plantController');
// plant routes
app.route('/plants')
.get(plantList.list_all_plants)
.post(plantList.create_new_plant);
app.route('/plants/:plantId')
.get(plantList.read_a_plant)
.put(plantList.update_a_plant)
.delete(plantList.delete_a_plant);
What I'd like to do is testing all this with Postman.
If I try with the GET method, using simply
http://localhost:3000/plants
everything works fine: I mean, it returns an empty array (mongodb is up and running, and everything is set).
Now I wanted to try to insert a new element with Postman: I selected POST and x-www-form-urlencoded under body. Required properties are plantData{genusObj{genus}} and plantData{species} : since I'm quite new with both postman and mongodb, how can I enter a sub-element in postman, to create a new Plant ?
there are only KEY and VALUE options, and i don't know how to write a sub-key like plantData->genusObj->genus.
P.S.: Suggestions on data model are welcome, I tried to build a generic plant database but oriented on tulips (so usually i can enter tulips, but if i need to enter something else, i can).
Well, it seems that this answer fits to me: in fact, on Postman i selected under "body" the "raw" option, then I selected JSON instead of TEXT from the dropdown menu, and finally I used this object (meanwhile I slightly changed the
model) - don't forget the " symbols everywhere, like I did - ' is not accepted:
{
"plantData": [
{
"family": "Liliaceae",
"genusObj": {
"genus": "Tulipa",
"tulipGroup": "Single Late",
"tulipGroupNumber": 5
},
"species": "TEST",
"sellName": "Queen of night",
"description": "black tulip",
"mainImage": "",
"otherImages": "",
"images": ""
}
],
"sellingData": [
{
"price": 0.50,
"availableQuantity": 100
}
],
"detailsData": [
{
"heightInCm": "60-65",
"floweringTime": "late spring",
"plantDepthCm": "20",
"plantSpacingCm": "10",
"bulbSizeInCm": "12",
"flowerColor": "Black",
"lightRequirements": "full sun"
}
]
}

how to remove _id from create replay mongodb node js

exports.createDD_PR_addresstype = asyncHandler(async (req, res, next) => {
const dropdowns = await DD_PR_addresstype.create(req.body);
res.status(200).json({
success: true,
data: dropdowns
});
});
replay
{
"success": true,
"data": {
"_id": "5f252a444824ac0164195c1a",
"label": "Battery",
"company_id": "5f17e0f4d6eded0db090b272",
"value": 1,
"__v": 0
}
}
i want to show only label and value. is there is any pre functions available to select created replay or i have to use seperate find query
You could destructure the query response:
const { label, value } = await DD_PR_addresstype.create(req.body);
res.status(200).json({
success: true,
data: { label, value }
});
But that's just a way to write less code for:
data: {
value: dropdowns.value,
label: dropdowns.label
}
If you're looking for retrieving the document later with only the given props then the projection answer (which was deleted in between) is the way to go.
Since the other projection answer was deleted I add it here (using _id just as example):
const dropdowns = await DD_PR_addresstype.find( { _id: "5f252a444824ac0164195c1a" }, { label: 1, value: 1 } )

Problem with ottoman not resolving the references

I have two models in my ottoman 1.0.5 setup. One holds contact info which includes an emails array of docs and then the email doc. I can insert new contacts fine as well as emails in docs and the corresponding link in the contact doc for the new email.
Here is my model
const ottoman = require("ottoman")
ottoman.bucket = require("../app").bucket
var ContactModel = ottoman.model("Contact",{
timestamp: {
type: "Date",
default: function() {return new Date()}
},
first_name : "string",
last_name : "string",
emails: [
{
ref:"Email"
}
]} )
var EmailModel = ottoman.model("Email",{
timestamp: {
type: "Date",
default: function() {return new Date()}
},
type : "string",
address : "string",
name: "string"
} )
module.exports = {
ContactModel : ContactModel,
EmailModel : EmailModel
}
Now to get an contact and all its emails i use this function
app.get("/contacts/:id", function(req, res){
model.ContactModel.getById(req.params.id,{load: ["emails"]}, function(error, contact){
if(error) {
res.status(400).json({ Success: false , Error: error, Message: ""})
}
res.status(200).json({ Success: true , Error: "", Message: "", Data : contact})
})
})
Which returns me this
{
"Success": true,
"Error": "",
"Message": "",
"Data": {
"timestamp": "2019-01-30T23:59:59.188Z",
"emails": [
{
"$ref": "Email",
"$id": "3ec07ba0-aaec-4fd4-a207-c4272cef8d66"
}
],
"_id": "0112f774-4b5d-4b73-b784-60fa9fa2f9ff",
"first_name": "Test",
"last_name": "User"
}
}
if i go and log the contact to my console i get this
OttomanModel(`Contact`, loaded, key:Contact|0112f774-4b5d-4b73-b784-60fa9fa2f9ff, {
timestamp: 2019-01-30T23:59:59.188Z,
emails: [ OttomanModel(`Email`, loaded, key:Email|3ec07ba0-aaec-4fd4-a207-c4272cef8d66, {
timestamp: 2019-01-31T00:36:01.264Z,
_id: '3ec07ba0-aaec-4fd4-a207-c4272cef8d66',
type: 'work',
address: 'test#outlook.com',
name: 'Test Outlook',
}),
OttomanModel(`Email`, loaded, key:Email|93848b71-7696-4ef5-979d-05c19be9d593, {
timestamp: 2019-01-31T04:12:40.603Z,
_id: '93848b71-7696-4ef5-979d-05c19be9d593',
type: 'work',
address: 'newTest#outlook.com',
name: 'Test2 Outlook',
}) ],
_id: '0112f774-4b5d-4b73-b784-60fa9fa2f9ff',
first_name: 'Test',
last_name: 'User',
})
This shows that emails was resolved but why does it not show up in the returned json. On the other hand if i return contact.emails i get the resolved emails just fine. So i hope someone can shed some light on what i am missing here
I asked a similar question on the couchbase forum, and I also found out the solution:
(a slight difference that the result of my search is an array not an object like in your case)
forum.couchbase.com
app.get("/assets", (req, res) => {
AssetModel.find({}, { load: ["assetModelId", "assetGroupId", "assetTypeId"] }, (err, results) => {
if (err) return res.status(400).send("no asset found");
const assets = [];
results.map(asset => {
assets.push({...asset});
});
res.status(200).send(assets)
});
});

updating values in nested object arrays Mongoose Schema

I have my schema designed like this
const templateSchema = new Schema({
Main: {
text: String,
textKey: String,
index: String,
part: String,
overallStatus: String,
subjects: [
{
id: String,
text: String,
textKey: String,
index: String,
type: String,
comment: String,
image: String,
answer: String,
}
and I have to update subjects text and subject id and I am doing it like this
router.post("/edit", (req, res, next) => {
Template.findOneAndUpdate({
id: req.body.id,
text: req.body.text
}).then(updatedTemp => {
console.log(updatedTemp);
if (updatedTemp) {
res.status(200).json({
message: "Template updated.."
});
} else {
res.status(404).json({
message: "Checklist not found"
});
}
});
});
it returns template updated and status 200 but it doesn't update the new values. How can i access subject ID and subject text in this schema
so, According to the provided schema,
you should find inside the array, and update there,
you could do something like this:
router.post("/edit", (req, res, next) => {
Template.update(
{
"Main.subjects.id": req.body.oldId,
"Main.subjects.text": req.body.oldText,
//you can pass some more conditions here
},
{
$set: {
"Main.subjects.$.id": req.body.id,
"Main.subjects.$.text": req.body.text
}
}
)
.then(updated => {
if (updated.nModified) {
res.status(200).json({
message: "Template updated.."
});
} else {
//not updated i guess
}
})
.catch(error => {
//on error
});
});
so payload in body you need to pass :
oldId : <which is currently there>,
oldText: <which is currently there>,
id: <by which we will replace the id field>
text:<by which we will replace the txt>
NOTE:
assuming , id or text will be unique among all the docs.
sample data:
{
"_id" : ObjectId("5be1728339b7984c8cd0e511"),
"phases" : [
{
"phase" : "insp-of-install",
"text" : "Inspection of installations",
"textKey" : "",
"index" : "1.0",
"subjects" : [...]
},...]
}
we can update text here like this [in the top most level]:
Template.update({
"_id":"5be1728339b7984c8cd0e511",
"phases.phase":"insp-of-install",
"phases.text":"Inspection of installations"
},{
"$set":{
"phases.$.text":"Some new text you want to set"
}
}).exec(...)
but, incase you want to do deep level nested update,
you can have a look at this answer : here by #nem035

Resources