Moongose: Insert Many Docs then get Id and Update another Doc in another Collection - mongodb

I have a collection of Users and Payments, and I need to add the Payments Id to their respective Users after they're created, but I don't find a eficient way of doing it.
const users = [
{
documentId: '123456789',
fullname: 'John Doe',
email: 'john#gmail.com',
payments: []
},
{
documentId: '987654321',
fullname: 'Fred Flinstone',
email: 'fred#gmail.com',
payments: []
},
{
documentId: '101010101',
fullname: 'Mary Poppins',
email: 'mary#gmail.com',
payments: []
}
]
const payments = [
{
billId: 1,
concept: 'Groceries',
amount: 10,
amountWithSymbol: '10$',
payHolder: 'John Doe'
},
{
billId: 2,
concept: 'Dinner',
amount: 15,
amountWithSymbol: '15$',
payHolder: 'John Doe'
}
{
billId: 3,
concept: 'Meal',
amount: 8,
amountWithSymbol: '8$',
payHolder: 'Fred Flinstone'
}
]
/*
I need to insert each payment get their Id and then add it to a User document.
This is the only way I found.
*/
payments.forEach(async pay => {
const paymentRecorded = await paymentsModel.create(pay);
const paymentUser = await usersModel.findOneAndUpdate(
{ fullname: pay.payHolder },
{ payments: [paymentRecorded._id] }
);
});
I know the way I do it, overwrites the previous recorded payments, so if you can solve that part too, I'd really appreciate it.

Related

Actions on google reservations for transaction API

We are building boot using action on builder SDK. In bot we have transaction related feature so we want to implement reservation feature to make appointment reservation. In our Bot we just need reservation. user can't cancel/delete reservation (As our member can contact the user for next 3 4 days, we are just asking user free time so we can contact user). (We did't have reservation feature yet but google team force us to do so). My Question is while implementing reservation we have https://developers.google.com/assistant/transactions/physical/dev-guide-physical-reservations#validate_transaction_requirements_optional this feature optional we are not implementing this, for second step we have to build Order like this https://developers.google.com/assistant/transactions/physical/dev-guide-physical-reservations#build_the_order
const order = {
createTime: '2019-09-24T18:00:00.877Z',
lastUpdateTime: '2019-09-24T18:00:00.877Z',
merchantOrderId: orderId, // A unique ID String for the order
userVisibleOrderId: orderId,
transactionMerchant: {
id: 'http://www.example.com',
name: 'Example Merchant',
},
contents: {
lineItems: [
{
id: 'LINE_ITEM_ID',
name: 'Dinner reservation',
description: 'A world of flavors all in one destination.',
reservation: {
status: 'PENDING',
userVisibleStatusLabel: 'Reservation is pending.',
type: 'RESTAURANT',
reservationTime: {
timeIso8601: '2020-01-16T01:30:15.01Z',
},
userAcceptableTimeRange: {
timeIso8601: '2020-01-15/2020-01-17',
},
partySize: 6,
staffFacilitators: [
{
name: 'John Smith',
},
],
location: {
zipCode: '94086',
city: 'Sunnyvale',
postalAddress: {
regionCode: 'US',
postalCode: '94086',
administrativeArea: 'CA',
locality: 'Sunnyvale',
addressLines: [
'222, Some other Street',
],
},
},
},
},
],
},
buyerInfo: {
email: 'janedoe#gmail.com',
firstName: 'Jane',
lastName: 'Doe',
displayName: 'Jane Doe',
},
followUpActions: [
{
type: 'VIEW_DETAILS',
title: 'View details',
openUrlAction: {
url: 'http://example.com',
},
},
{
type: 'CALL',
title: 'Call us',
openUrlAction: {
url: 'tel:+16501112222',
},
},
{
type: 'EMAIL',
title: 'Email us',
openUrlAction: {
url: 'mailto:person#example.com',
},
},
],
termsOfServiceUrl: 'http://www.example.com'
};
According to doc we have to create order object like above, but we are unable to find any doc what are optional filed in above object and what value to pass for reservationTime and userAcceptableTimeRange.
reservationTime: {
timeIso8601: '2020-01-16T01:30:15.01Z',
},
userAcceptableTimeRange: {
timeIso8601: '2020-01-15/2020-01-17',
}
Further more do we need to implement Set up asynchronous requests to the Orders API (https://developers.google.com/assistant/transactions/physical/dev-guide-physical-reservations#set_up_asynchronous_requests_to_the_orders_api) as we don't need to update user appoint time and user can't cancel appointment.
Is there any other way we can avoid reservation? please guide me, thanks in advance.

how to create a flexible number of posts using prisma

This might not be possible but is there a way to create an flexible amount of posts in prisma. For example, I have a user and I would like them to create be able to create any amount of posts at once, so it would be one post or three posts. Is this possible using Prisma?
Here is the query I'm using:
const user = await prisma.user.update({
where: {
id: 9,
},
data: {
posts: {
// This is where I would like to make the amount of posts being created on the frontend flexible
createMany: {
data: [{ title: 'My first post' }, { title: 'My second post' }],
},
},
},
})
Here you go an example how to do that:
const { PrismaClient } = require('#prisma/client')
const prisma = new PrismaClient()
const saveData = async () => {
const user = await prisma.user.create({
data: {
name: 'John Doe',
posts: {
createMany: {
data: [
{
title: 'First Post',
},
],
}
}
},
include: {
posts: true
}
})
console.log(JSON.stringify(user, null, 2));
await prisma.user.update({
where: {
id: user.id
},
data: {
posts: {
createMany: {
data: [
{
title: 'Second Post',
},
{
title: 'Third Post',
}
],
}
}
}
})
console.log(JSON.stringify(await prisma.user.findMany({ include: {posts: true} }), null, 2));
}
saveData()
And here you go the result

Find if an array present in the mongo Database

This is my Conversation Schema
const ConversationSchema = new Schema({
recipients: [{ type: Schema.Types.ObjectId, ref : 'User' }],
lastMessage: {
type: String,
default: ''
},
date: {
type: Date,
default: Date.now()
},
})
I want to know if there exist an array [ patientId, doctorId ]
Here is my main approach to find
I am not able to get the response and I already have one document with that same array
const conversationBetween = await Conversation.findOne(
{
recipients: {
$all: [
{ $elemMatch: { $eq: patientId }},
{ $elemMatch: { $eq: doctorId }}
],
}
}
)
if (conversationBetween) {
return res.status(401).json({
status: "failed",
message: "You already have a conversation with this doctor"
});
}
following Code to add a Conversation in the Conversation Collection, this works fine
const newConversation = new Conversation({
recipients: [ patientId,doctorId ],
lastMessage: `I want to get consultation`,
date: Date.now(),
})
await newConversation.save()
res.status(200).json({
status: "success",
message: "Conversation added successfully",
conversation: newConversation
});
The main purpose is to make sure that if there present an entry with [ patientId, doctorId ] in Conversation it should not make a new entry..
But at this time its not able to find and is making that same entry.
You can do this
await Conversation.findOne(
{
recipients: [patientId, doctorId]
}
)
Working in Playground

How to append data to existing array in mongodb in MERN stack

I have an existing array which looks like this
{
_id: 5f14675a4fb8565fb89ec338,
name: 'sample5',
email: 'sample5#test.com',
rollno: 9,
city: [
{
_id: 5f14675a4fb8565fb89ec339,
cityname: 'Sample City 1',
citycode: '000000'
}
],
__v: 0
}
So I want to append the data to the existing array which is
city: [
{
_id: 5f14675a4fb8565fb89ec339,
cityname: 'Sample City 2',
citycode: '000002'
}
],
So my final db should look like this
{
_id: 5f14675a4fb8565fb89ec338,
name: 'sample5',
email: 'sample5#test.com',
rollno: 9,
city: [
{
_id: 5f14675a4fb8565fb89ec339,
cityname: 'Sample City 1',
citycode: '000000'
},
{
_id: 5f14675a4fb8565fb89ec339,
cityname: 'Sample City 2',
citycode: '000002'
},
],
__v: 0
}
For now I am just able to update my existing data where I show the cityname and citycode and if the user make any changes it is reflected in the database.
Code I am using to update the database
// Update Student
router.route('/update-student/:id').put((req, res, next) => {
studentSchema.findByIdAndUpdate(req.params.id, {
$set: req.body
}, (error, data) => {
if (error) {
return next(error);
console.log(error)
} else {
// $push:{
res.json(data)
console.log('Student updated successfully !')
// }
}
})
})
Schema structure
let studentSchema = new Schema({
name: {
type: String
},
email: {
type: String
},
rollno: {
type: Number
},
city: [{
cityname: {type: String},
citycode: {type: String},
}],
},
{
collection: 'students'
})
And then in routes it is updated using $push method
// Update Student
router.route('/update-student/:id').put((req, res, next) => {
studentSchema.findByIdAndUpdate(req.params.id, {
$push: req.body
}, (error, data) => {
if (error) {
return next(error);
console.log(error)
} else {
// $push:{
res.json(data)
console.log('Student updated successfully !')
// }
}
})
})
OUTPUT
[{_id: "5f12e5158be2503422bf6982", name: "sample1", email: "sample1#test.com", rollno: 1,…},…]
0: {_id: "5f12e5158be2503422bf6982", name: "sample1", email: "sample1#test.com", rollno: 1,…}
city: [{_id: "5f146fb84fb8565fb89ec33c", cityname: "city3", citycode: "12345"},…]
0: {_id: "5f146fb84fb8565fb89ec33c", cityname: "city3", citycode: "12345"}
citycode: "12345"
cityname: "city3"
_id: "5f146fb84fb8565fb89ec33c"
1: {_id: "5f15301f67c1992f4a233f77", cityname: "new city", citycode: "new code"}
citycode: "new code"
cityname: "new city"
_id: "5f15301f67c1992f4a233f77"
email: "sample1#test.com"
name: "sample1"
rollno: 1
__v: 0
_id: "5f12e5158be2503422bf6982"
Check out This answer you might need to use the $push in your query to achieve what you want.
SOLUTION
When the submit button is clicked. The array is stored in city as the schema is in this manner. This schema structure is there above. It is then passed to the db using axios.
onSubmit(e) {
e.preventDefault()
const studentObject = {
city: [{cityname: this.state.cityname, citycode: this.state.citycode}]
};
axios.put('http://localhost:4000/students/update-student/' + this.props.match.params.id, studentObject)
.then((res) => {
console.log(res.data)
console.log('Student successfully updated')
}).catch((error) => {
console.log(error)
})
// Redirect to Student List
this.props.history.push('/student-list')
}

mongoose response odd format

What I'm trying to do is let the user get a list of posts that they have added to their favorites which is done by simply putting their _id into the post's favorites array.
when running that particular query, it comes back as an array with unnamed entries along with _locals in the array.
I need something more like Posts: [ {}, {} ], _locals.
How do I get it into that format?
var UserSchema = new Schema({
username : String,
firstName : String,
lastName : String,
email : String,
password : String
});
var PostSchema = new Schema({
author : { type: Schema.Types.ObjectId, ref: 'User' },
date : Date,
body : String,
username : String,
sid : String,
views : Number,
likes : [{ type: Schema.Types.ObjectId, ref: 'User' }],
favorites : [{ type: Schema.Types.ObjectId, ref: 'User' }]
});
and the get
app.get('/favorites', function(req, res) {
Post
.find({ 'favorites': '58f4f9e5650785228016287f'})
.exec(function(err, favorites) {
res.render('favorites', favorites)
console.log(favorites)
})
});
I get a response of
[ { _id: 58f4f9e96507852280162880,
author: 58f4f9e5650785228016287f,
body: 'test',
date: 2017-04-17T17:22:49.059Z,
username: 'test',
sid: 'BJ-xquGRl',
__v: 2,
favorites: [ 58f4f9e5650785228016287f ],
likes: [] },
{ _id: 58f500edd8abc7242c90d61c,
author: 58f4f9e5650785228016287f,
body: 'w00p w00p',
date: 2017-04-17T17:52:45.612Z,
username: 'test',
sid: 'BJ8g-tG0e',
__v: 1,
favorites: [ 58f4f9e5650785228016287f ],
likes: [] },
_locals: { user:
{ id: 58f4f9e5650785228016287f,
username: 'test',
firstName: 'test',
lastName: 'test',
email: 'test#test.com' } } ]
That _locals is something that Express adds to the object that you pass to res.render(). If you would reverse the function calls you made, it wouldn't be there anymore:
console.log(favorites);
res.render('favorites', favorites);
However, the main issue is that you're passing an array (favorites) as argument to res.render(), which expects an object instead. The correct way of calling it would be by passing favorites as an object value:
res.render('favorites', { favorites : favorites });
// Or in recent Node versions:
// res.render('favorites', { favorites });