I am trying to store order data but getting following error when adding it to mongoose:
Request:
Response:
Here is my source Code:
placeOrder Handler:
const placeOrderHandler = () => {
dispatch(
createOrder({
orderItems: cartItems,
shippingAddress: {
address: shippingAddress.address,
city: shippingAddress.city,
postalCode: shippingAddress.postalCode,
country: shippingAddress.country,
},
paymentMethod: paymentMethod,
itemPrice: cart.itemPrice,
shippingPrice: cart.shippingPrice,
taxPrice: cart.taxPrice,
totalPrice: cart.totalPrice,
})
);
};
orderModel.js
const mongoose = require("mongoose");
const orderSchema = mongoose.Schema(
{
user: {
type: mongoose.Schema.Types.ObjectId,
required: true,
ref: "User",
},
orderItems: [
{
name: { type: String, required: true },
qty: { type: Number, required: true },
image: { type: String, required: true },
price: { type: Number, required: true },
product: {
type: mongoose.Schema.Types.ObjectId,
required: true,
ref: 'Product',
},
},
],
shippingAddress: {
address: { type: String, required: true },
city: { type: String, required: true },
postalCode: { type: String, required: true },
country: { type: String, required: true },
},
paymentMethod: {
type: String,
required: true,
},
paymentResult: {
id: { type: String },
status: { type: String },
update_time: { type: String },
email_address: { type: String },
},
taxPrice: {
type: Number,
required: true,
default: 0.0,
},
shippingPrice: {
type: Number,
required: true,
default: 0.0,
},
totalPrice: {
type: Number,
required: true,
default: 0.0,
},
isPaid: {
type: Boolean,
required: true,
default: false,
},
paidAt: {
type: Date,
},
isDelivered: {
type: Boolean,
required: true,
default: false,
},
deliveredAt: {
type: Date,
},
},
{
timestamps: true,
}
);
const Order = mongoose.model("Order", orderSchema);
module.exports = Order;
If I am not wrong it is throwing error on orderItems:, but I am sending array of objects data which I have already defined in my orderModel.js.
As #Ernesto mentioned I was writing product in my schema instead of productID. Here is the correct way:
orderItems: [
{
name: { type: String, required: true },
qty: { type: Number, required: true },
image: { type: String, required: true },
price: { type: Number, required: true },
productID: {
type: mongoose.Schema.Types.ObjectId,
required: true,
ref: 'Product',
},
},
],
Related
I want to use data returned by a map method into another function.
Here is the route schema:
const routeSchema = new mongoose.Schema(
{
Location: {
from: {
type: mongoose.Schema.Types.ObjectId,
ref: "Location",
required: true,
},
to: {
type: mongoose.Schema.Types.ObjectId,
ref: "Location",
required: true,
},
},
busId: {
type: mongoose.Schema.Types.ObjectId,
ref: "Bus",
required: true,
},
date: {
type: String,
required: true,
},
departureTime: {
type: Number,
required: true,
},
arrivalTime: {
type: Number,
required: true,
},
},
{
timestamps: true,
}
);
and here is the booking schema and in booking table routeId is embedded:
const bookingSchema = new mongoose.Schema({
userId: {
type: mongoose.Schema.Types.ObjectId,
ref: "User",
required: true,
},
routeId: {
type: mongoose.Schema.Types.ObjectId,
ref: "Route",
required: true,
},
passengers: [
{
name: { type: String, required: true, trim: true },
gender: { type: String, required: true, trim: true },
age: { type: Number, required: true, trim: true },
}],
phone: {
type: Number,
required: true,
},
email: {
type: String,
required: true,
},
bookingDate: {
type: String,
required: true,
},
fare: {
type: Number,
required: true,
},
seats: {
type: [Number],
required: true,
},
departureDetails: [
{
city: { type: String, required: true, trim: true },
location: { type: String, required: true, trim: true },
time: { type: String, required: true, trim: true },
date: { type: String, required: true, trim: true },
},
],
arrivalDetails: [
{
city: { type: String, required: true, trim: true },
location: { type: String, required: true, trim: true },
time: { type: String, required: true, trim: true },
date: { type: String, required: true, trim: true },
},
],
},{
timestamps:true
});
Here is the map function method:
router.get("/trip/single", async (req, res) => {
if (!req.query.from || !req.query.to || !req.query.date) {
return res.send({
error: "Please enter the data to get the trip",
});
}
const { from, to, date } = req.query;
const routes = await Route.find({
"Location.from": from,
"Location.to": to,
"date": date.toString(),
});
const matchedBus = await routes.filter(() =>{
return Route.busId === routes._id
});
const bookings = await Booking.find({
routeId: { $in: matchedBus.map((matchedBus) => matchedBus._id) },
});
console.log(bookings);
const busIdWithSeatsObj = {};
var busData = matchedBus.map(data => data)
console.log(busData);
This busData console is returning this data:
[
{
Location: {
from: new ObjectId("6295f0986f9e32990d8b3488"),
to: new ObjectId("6295f0c06f9e32990d8b348b")
},
_id: new ObjectId("6295f12c6f9e32990d8b348e"),
busId: new ObjectId("6295f0836f9e32990d8b3485"),
date: '2022-06-02',
departureTime: 11,
arrivalTime: 6.3,
createdAt: 2022-05-31T10:42:52.785Z,
updatedAt: 2022-05-31T10:42:52.785Z,
__v: 0
}
]
Now I want to use only busId and date only in the function below:
for (let i = 0; i < matchedBus.length; i++) {
let currentBusSeats = [];
const busBookings = bookings.filter((booking) => {
return (
//Want to use date and busId data in here
//someData === date.toString() &&
//someData === matchedBus[i]._id
);
});
console.log(busBookings);
busBookings.forEach(() => {
currentBusSeats = [...currentBusSeats, ...Booking.seats];
});
busIdWithSeatsObj[matchedBus[i]._id] = currentBusSeats;
}
res.status(200).send({ routes, matchedBus, busIdWithSeatsObj });
});
How can I do that to get the result?
var busData = matchedBus.map(data => data
'use your for loop inside data and you can get you _id value by data._id'
)
Here is my orders schema with Javascript mongoose;
import mongoose from 'mongoose';
const orderSchema = new mongoose.Schema(
{
orderItems: [
{
name: { type: String, required: true },
qty: { type: Number, required: true },
image: { type: String, required: true },
price: { type: Number, required: true },
product: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Product',
required: true,
},
},
],
shippingAddress: {
fullName: { type: String, required: true },
address: { type: String, required: true },
city: { type: String, required: true },
postalCode: { type: String, required: true },
country: { type: String, required: true },
lat: Number,
lng: Number,
},
paymentMethod: { type: String, required: true },
paymentResult: {
id: String,
status: String,
update_time: String,
email_address: String,
},
itemsPrice: { type: Number, required: true },
shippingPrice: { type: Number, required: true },
taxPrice: { type: Number, required: true },
totalPrice: { type: Number, required: true },
user: { type: mongoose.Schema.Types.ObjectId, ref: 'User', required: true },
seller: { type: mongoose.Schema.Types.ObjectID, ref: 'User' },
isPaid: { type: Boolean, default: false },
paidAt: { type: Date },
isDelivered: { type: Boolean, default: false },
deliveredAt: { type: Date },
},
{
timestamps: true,
}
);
const Order = mongoose.model('Order', orderSchema);
export default Order;
And for the case of sellers how could I do the same for specific sellers.
I would like to create charts and graphs with that data so any help counts. Thank You!
I have a mini casino game and have a mongoose model defined as following:
const jackpotSchema = mongoose.Schema({
round_id: {
type: String,
default: uniqid(),
required: true,
},
createdAt: {
type: Date,
required: true,
default: Date.now
},
closedAt: {
type: Date,
},
startedAt: {
type: Number,
},
roundSecret: {
type: String,
required: true,
},
random_org_hash: {
type: String,
},
random_org_obj: {
type: String
},
roundSecretHash: {
type: String,
},
winningPercentage: {
type: Number,
// required: true,
// first 5 characters of the secret hash, converted into decimal then divided by 10K
},
publicHash: {
type: String,
required: true,
// SHA-256 roundSecret + winningPercentage
},
finalHash: {
type: String,
},
winningTicket: {
type: Number,
},
winningDepositIndex: {
type: Number,
},
deposits: [{
uid: {
type: String,
required: true,
},
user: {
type: String,
required: true,
},
nonce: {
type: Number,
},
amount: {
type: Number,
required: true,
},
user_avatar: {
type: String,
},
ticketRangeMin: {
type: Number,
required: true,
},
ticketRangeMax: {
type: Number,
required: true,
},
referral: {type: String},
timestamp: {type: Date},
timestamp_readable: {type: String}
}],
total: {
type: Number,
required: true,
default: 0,
},
totalTickets: {
type: Number,
default: 0,
},
winner: {
type: String,
default: "",
},
winner_avatar: {
type: String,
},
active: {
type: Boolean,
default: true,
required: true,
},
open: {
type: Boolean,
required: true,
default: true,
},
roundTime: {
type: Number,
// default: potConfig.potLength,
default: 20000,
},
success: {
type: Boolean,
},
fee: {
type: Number,
default: potConfig.potFee,
}
})
module.exports = mongoose.model("Jackpot", jackpotSchema)
When running my app locally, I experience no errors.
However when running on a ubuntu production environment, I get the following error:
Jackpot.find is not a function
The stack trace says that the error is coming from db_utils.js
which looks like the following:
const Jackpot = require("./models/Jackpot");
...
async retrieveStats () {
var jackpots = await Jackpot.find().lean();
}
I have checked to see whether my module.exports was defined correctly, and it is. Not sure why this error is happening.
My local and production node versions match.
12.18.4
Don't you need to do
const jackpotSchema = new mongoose.Schema({...})
instead of
const jackpotSchema = mongoose.Schema({...})
I want to store some data in the following MongoDB model:
import mongoose from 'mongoose';
const orderSchema = mongoose.Schema(
{
user: {
type: mongoose.Schema.Types.ObjectId,
required: true,
ref: 'User',
},
orderItems: [
{
name: { type: String, required: true },
qty: { type: Number, required: true },
image: { type: String, required: true },
price: { type: Number, required: true },
product: {
type: mongoose.Schema.Types.ObjectId,
required: true,
ref: 'Product',
},
},
],
shippingAdress: {
address: { type: String, required: true },
city: { type: String, required: true },
postalCode: { type: String, required: true },
state: { type: String, required: false },
country: { type: String, required: true },
},
paymentMethod: {
type: String,
required: true,
},
paymentResult: {
id: { type: String },
status: { type: String },
update_time: { type: String },
email_address: { type: String },
},
taxPrice: {
type: Number,
required: true,
default: 0.0,
},
shippingPrice: {
type: Number,
required: true,
default: 0.0,
},
totalPrice: {
type: Number,
required: true,
default: 0.0,
},
isPaid: {
type: Boolean,
required: true,
default: false,
},
paidAt: {
type: Date,
},
isDelivered: {
type: Boolean,
required: true,
default: false,
},
deliveredAt: {
type: Date,
},
},
{ timestamps: true }
);
const Order = mongoose.model('Order', orderSchema);
export default Order;
But I am not able to post the following sample data to the database
{
"orderItems": [
{
"product": "6060f2eb6bea3f2280c08a4c",
"name": "Airpods Wireless Bluetooth Headphones",
"image": "/images/airpods.jpg",
"price": 89.99,
"qty": 3
}
],
"user": "6060f2eb6bea3f2280c08a4b",
"shippingAddress": {
"address": "1st Avenue Main St",
"city": "Boston",
"postalCode": "02011",
"country": "USA"
},
"paymentMethod": "Stripe",
"itemsPrice": 269.97,
"taxPrice": 40.50,
"shippingPrice": 20.00,
"totalPrice": 330.47
}
as I get the following error:
By the way I am trying to get that done through Postman
"Order validation failed: shippingAdress.country: Path shippingAdress.country is required., shippingAdress.postalCode: Path shippingAdress.postalCode is required., shippingAdress.city: Path shippingAdress.city is required., shippingAdress.address: Path shippingAdress.address is required."
You have a typo in your Model shippingAdress. It should be shippingAddress.
I have a model in Mongoose that looks like this:
const orderLogSchema = mongoose.Schema(
{
removed: { type: String, required: true },
},
{
timestamps: true,
}
)
const orderSchema = mongoose.Schema({
user: {
type: mongoose.Schema.Types.ObjectId,
required: true,
ref: 'User'
},
orderItems: [
{
name: { type: String, required: true},
qty: { type: Number, required: true},
image: { type: String, required: true},
price: { type: Number, required: true},
product: { type: mongoose.Schema.Types.ObjectId, required: true, ref: 'Product'},
}
],
shippingAddress: {
address: { type: String, required: true },
city: { type: String, required: true },
postalCode: { type: String, required: true },
country: { type: String, required: true },
},
paymentMethod: {
type: String,
required: true,
},
paymentResult: {
id: { type: String },
status: { type: String },
update_time: { type: String },
email_address: { type: String },
},
taxPrice: {
type: Number,
required: true,
default: 0.0
},
shippingPrice: {
type: Number,
required: true,
default: 0.0
},
totalPrice: {
type: Number,
required: true,
default: 0.0
},
isPaid: {
type: Boolean,
required: true,
default: false
},
paidAt: {
type: Date,
},
isDelivered: {
type: Boolean,
required: true,
default: false
},
deliveredAt: {
type: Date,
},
couponCode: {
type: Object,
required: false
},
orderVerifyLog: [orderLogSchema],
}, {
timestamps: true
})
I need to be able to empty out the orderVerifyLog which is populated with the orderLogSchema. I have tried a bunch of things most recently I pulled the order into a variable, and I am able to access orderVerifyLog by using order.orderVerifyLog but I cant figure out how to empty out that orderLogSchema. I tried:
order.orderVerifyLog = []
order.save()
Is there an easy way to work with that "sub" schema and zero it out?
Basically I am pulling the log items from that schema for an order and displaying them on my front-end. Then I was to fire off an action to clears it out so they don't display every time the order is loaded (Only want them to show once). I also tired to loop over each item in the orderVerifyLog and use pull to remove them, but for some reason it always leaves one in there.