im having trouble in creating an array in postman.
What I want is to post this in the request.body(postman/insomnia)..
{
"nama": "tests",
"afco_id": 2,
"business_area_id": 10,
"approval_level": [
{
"sequence_level": 1,
"user_id": 1
},
{
"sequence_level": 2,
"user_id": 2
},
{
"sequence_level": 3,
"user_id": 3
}
]
}
and this is my controller code:
const postApprovalMaster = async (req, res) => {
return (
db.Bb_t2_Approval.create(
{
nama: req.body.nama,
afco_id: req.body.afco_id,
business_area_id: req.body.business_area_id,
approval_level: [req.body]
},
{
include: [
{
model: db.Bb_t3_Approval_Level,
as: "approval_level",
},
{
model: db.Bb_t1_Organisasi,
as: "afco",
},
{
model: db.Bb_t1_Organisasi,
as: "business_area",
},
],
}
).then((result) =>
res.status(201).json({
data: result,
status: true,
message: "Created new approval master success",
})
)
.catch((err) => {
res.status(400).json({
status: false,
message: err.message,
})
})
)
}
whenever i hardcoded the req.body into the controllers approval_level, it works just fine. but i dont want it like that
can anyone help? thanks a lot I appreciate it
You can either try this
Solution 1
or if this doesnt work with node.js you can also try to just write the array attribute like this.
Solution 2
One of those should work.
I can't comment and I'd love to help but can you try to give more examples or explain a little more #Hafizh Farhandika
Related
This my API Code .it work perfectly but missing my "startedDate":"2022-01-01", and
"endDate":"2022-01-31" … how I write the the function pls solved my problem and share your idea..
async getcurrentmonthorder2(req, res, next) {
try {
const {startedDate ,endDate} = req.body;
db.product.findAll({
attributes:[[sequelize.fn('sum',sequelize.col('profit_total')),'total']],
where : {"createdAt" : {[Op.between] : [new Date(startedDate).setHours(0,0,0,0) , new Date(endDate).setHours(23,59,59,999) ]}},
})
.then(list => {
res.status(200).json({ 'success': true, data: list });
})
.catch(function (err) {
next(err)
});
}
catch (err) {
res.status(500).json({ 'errors': "" + err });
}
}
#I have got output from postman..
{
"success": true,
"data": [
{
"total": "121",
}
]
}
#but I want to this output pls help share your idea
{
"success": true,
"data": [
{
"total": "121",
"startedDate":"2022-01-01",
"endDate":"2022-01-31"
}
]
}
my data
{id: 1, total: 20, profit_total: 15, createdAt: "2021-12-30T15:59:10.000Z",…}
Your problem comes from the attributes which you indicated in your query: You told SEQUELIZE to return only TOTAL. I suggest you this::
db.product.findAll({
attributes:[[sequelize.fn('sum',sequelize.col('profit_total')),'total'], 'startedDate', 'endDate'],
where : {
"createdAt" : {
[Op.between] : [new Date(startedDate).setHours(0,0,0,0), new Date(endDate).setHours(23,59,59,999) ]}
},
})
I'm trying to get all documents from my database collection "posts" but I'm getting an empty array instead.
The strange thing is that I'm able to get all documents from another collection called "users" that has the same structure and using the exact same code.
I've spent days looking for an answer but I haven't been able to find the solution.
This is the request:
const db = admin.firestore();
exports.getAllPosts = (req, res) => {
db.collection('posts')
.orderBy('createdAt', 'desc')
.get()
.then(snapshot => {
let posts = [];
snapshot.forEach((doc) => {
posts.push({
id: doc.id,
body: doc.data().body,
author: doc.data().author,
createdAt: doc.data().timestamp,
voteScore: doc.data().voteScore
});
});
return res.json(posts);
})
.catch(err => {
console.error(err);
res.status(500).json({ error: err.code });
});
}
And this is the response:
[]
This is what my current collection looks like:
Posts collection screenshot
This the response that I get when I return "snapshot":
{
"_query": {
"_firestore": {
"_settings": {
"projectId": "readable-bf7a6",
"firebaseVersion": "9.6.0",
"libName": "gccl",
"libVersion": "4.10.0 fire/9.6.0"
},
"_settingsFrozen": true,
"_serializer": {
"allowUndefined": false
},
"_projectId": "readable-bf7a6",
"registeredListenersCount": 0,
"bulkWritersCount": 0,
"_backoffSettings": {
"initialDelayMs": 100,
"maxDelayMs": 60000,
"backoffFactor": 1.3
},
"_clientPool": {
"concurrentOperationLimit": 100,
"maxIdleClients": 1,
"activeClients": {},
"failedClients": {},
"terminated": false,
"terminateDeferred": {
"promise": {}
}
}
},
"_queryOptions": {
"parentPath": {
"segments": []
},
"collectionId": "posts",
"converter": {},
"allDescendants": false,
"fieldFilters": [],
"fieldOrders": [
{
"field": {
"segments": [
"createdAt"
]
},
"direction": "DESCENDING"
}
],
"kindless": false
},
"_serializer": {
"allowUndefined": false
},
"_allowUndefined": false
},
"_readTime": {
"_seconds": 1622395245,
"_nanoseconds": 513743000
},
"_size": 0,
"_materializedDocs": null,
"_materializedChanges": null
}
Notice how the request for the collection "users" works successfully:
const db = admin.firestore();
exports.getAllUsers = (req, res) => {
db.collection('users')
.orderBy('createdAt', 'desc')
.get()
.then(snapshot => {
let users = [];
snapshot.forEach((doc) => {
let users = [];
snapshot.forEach((doc) => {
users.push({
id: doc.data().userId,
email: doc.data().email,
handle: doc.data().handle
});
});
return res.json(users);
})
.catch(err => {
console.error(err);
res.status(500).json({ error: err.code });
});
}
And the response:
[
{
"id": "EPoHBxhQFUXbcL3TCVx1LdUG2nO2",
"email": "ruben#gmail.com"
},
{
"id": "RqEa3dEq8TSDcZYeolXafju67rB2",
"email": "user10#gmail.com"
},
{
"id": "dxveb4n2iMQej5Q14uprsKRxFp23",
"email": "user4#gmail.com",
"handle": "user4"
},
{
"id": "YQPzBPcsqlVZk9iJEuZTHKUNuVG2",
"email": "user2#gmail.com",
"handle": "user2"
},
{
"id": "CZ05BJxi3TUOpIrmBaz539OWlbC3",
"email": "user#gmail.com",
"handle": "user"
},
{
"id": "t0t83BVwt4gVgJkDv7HL1r1MaKr1",
"email": "userJose2#gmail.com",
"handle": "Jose"
}
]
This is what the users collection looks like in Firebase:
Users collection screenshot
Why is one collection failing when the other works fine and I'm using the same code? What am I missing here?
Thanks in advance and I hope I've made it as clear as possible. Please let me know if you need me to provide anything else.
Very simple my friend, your posts documents can't be ordered like this:
.orderBy('createdAt', 'desc')
Because the post documents does not have the createdAt property, but they have a timestamp property, you should use that property to order your posts like this:
.orderBy('timestamp', 'desc')
I hope that helps 👍
I am not answering directly to #Ruben Garcia Bri, but for future firebase developers who may run into the problem of getting empty documents, I also ran into the same problem, but I solved it by adding a field to the particular document I am trying to retrieve.
Sometimes the cause is because the documents you are trying to get have no field in them.
I mean that a document must have a field before the server can recognize it as an existing document.
So if you run into this problem, consider adding a field to that document before you can successfully retrieve it.
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 } )
How can I remove an object from my array? I am currently using express/node and mongo/mongoose. I am struggling to remove a specific object from my array. Here is what I have so far.
// Favorites object
{
_id: "12931402dnfervo34fjo3",
favorites: [
{id: 1, name: "test"}, // I want to delete this (at index 0)
{id: 2, name: "test2"},
{id: 3, name: "test3"},
]
}
// DELETE /user/{id}/favorites/{index}
router.delete('/favorites/:itemid', auth, (req, res) => {
Favorites.updateOne({
_id: req.session.user
}, {
$pull: {
"favorites": {
"id": req.params.itemid
}
}
}, {
safe: true,
multi: true
})
.then(response => res.status(200).json(response))
.catch(err => res.status(400).json({
message: err.message,
error: true
}))
});
is there something I am missing from this code?
In the sample document the id field in the favorites array is integer, but you are querying with req.params.itemid which is usually string.
Converting that to integer should help.
$pull: { "favorites": { "id": parseInt(req.params.itemid) } }
I'm developing an API that shows the bulletin boards list.
And it also shows one of the latest posts at the same time.
In controller I coded like this
exports.boards_get_all = (req, res, next)=>{
Board.find()
.exec()
.then(boards=>{
res.status(200).json({
count: boards.length,
boards: boards.map(board=>{
return {
board: {
id:board._id,
name: board.name,
order: board.order
},
post : Post.findOne({boardId:board._id})
.exec()
.then(posts=>{
console.log(posts)
return posts;
}
)
}
})
})
})
}
I use findOne() and try to return what Post found
but return post didn't work. just return empty value.
result :
{
"count": 1,
"boards": [
{
"board": {
"id": "5eb23f1fed38dc5dfc2debfd",
"name": "QnA board",
"order": 1
},
"post": {}
}
]
}
I think I took the wrong approach about using findOne()...
I want to get result like this
{
"count": 1,
"boards": [
{
"board": {
"id": "5eb23f1fed38dc5dfc2debfd",
"name": "QnA board",
"order": 1
},
"post": {
_id: 5eb364a27989ab6f414fcdb1,
userId: 5eb2aad669738d67b5497f3a,
boardId: 5eb23f1fed38dc5dfc2debfd,
type: 1,
title: 'this is a latest post in QnA board',
content: 'Sample content',
like: 0,
comment: 0,
view: 1,
date: 2020-05-07T01:30:10.957Z,
thumb: 'pic url',
__v: 0
}
}
]
}
The post is {} because the res.status(200).json() is executed and returned before the findOne callback returns a value.
To fix this, you need to get the post documents from the database before calling res.status(200).json().