there is a way to set ttl (expire time?) while saving the data in the db ?
i have this schema :
const mongoose = require("mongoose");
const { ObjectId } = mongoose.Schema;
const productSchema = new mongoose.Schema(
{
name: {
type: String,
trim: true,
required: true,
maxlength: 255,
},
description: {
type: String,
trim: true,
required: true,
maxlength: 2000,
},
discountprice: {
type: Number,
maxlength: 32,
trim: true,
},
price: {
type: Number,
required: true,
maxlength: 32,
trim: true,
},
photo: String,
},
{ timestamps: true }
);
module.exports = mongoose.model("Product", productSchema);
i would like to set up a expire date for each product while saving ...
how do i save the product :
var product = {
name: item.title,
description: item.description,
photo: item.image,
discountprice: item.deal_price.value,
price: item.list_price.value,
};
let prodotto = new Product(product);
prodotto.save((err, prodotto) => {
if (err) {
console.log(err);
}
});
how can i set up exipire time here ?
If you do not want to add the expiration date to your model then simply pass the expiration as a variable in your product object.
var product = {
name: item.title,
description: item.description,
photo: item.image,
discountprice: item.deal_price.value,
price: item.list_price.value,
expiration: <some_value/variable>
};
Related
I want to add an auto-increment field in the MongoDB schema for
Interview.round.count field i.e. whenever I will Update the interview field it will automatically increase the Count value with +1
//Here is My Schema Field
const mongoose = require('mongoose');
const mongoosePaginate = require('mongoose-paginate-v2');
const { Schema } = mongoose;
const InterviewSchema = new Schema(
{
name: {
type: String,
required: true,
trim: true,
maxlength: 30,
},
email: {
type: String,
required: true,
trim: true,
},
gender: {
type: String,
required: true,
},
contactNumber: {
type: Number,
required: true,
}
interview: [
{
interviewerName: {
type: String,
trim: true,
},
round: {
count: {
type: Number,
default: 0,
},
type: {
type: String,
default: 'telephonic',
},
},
recommendation: {
type: String,
default: '',
},
},
],
},
},
{
timestamps: true,
},
);
InterviewSchema.plugin(mongoosePaginate);
const InterviewProcess = mongoose.model('interviewprocess', InterviewSchema);
module.exports = InterviewProcess;
Interview schema is defined as an array object.
My goal is to auto-increment the Interview.round.count i.e. for the count field
Can anyone please help me?
I have a "cart" model, and within my "order" model, I would like to have an array that receives the information sent by "cart" stored in an array. How can I do this through ref?
const mongoose = require('mongoose');
const CartSchema = new mongoose.Schema(
{
name: {
type: String,
required: true,
},
note: {
type: String,
required: true,
},
price: {
type: Number,
required: false,
},
createdAt: {
type: Date,
default: Date.now,
}
},
{ timestamps: true }
);
module.exports = mongoose.model("Cart", CartSchema);
order
const mongoose = require('mongoose');
const OrderSchema = new mongoose.Schema(
{
list: {
name: String,
notes: String,
},
totalAmount: {
type: Number,
required: true,
},
payment: {
type: String,
required: true,
},
address: {
type: String,
required: true,
},
addressNote: {
type: String,
required: false,
},
createdAt: {
type: Date,
default: Date.now,
}
},
{ timestamps: true }
);
module.exports = mongoose.model("Order", OrderSchema);
Here in "list" I would like it to be an array that receives cart model information
Can I do this through ref? What would be the best possible way?
I have a category model and product model. i refer category model from product model in category property of schema by using ref:"Category" . when i search in web that show for ref we need to first require the model. but instructor did not require category model in product he just export it . so is ref works here because i cannot understand it works or not ??
category model-->
const mongoose = require("mongoose");
const categorySchema = new mongoose.Schema(
{
name: {
type: String,
trim: true,
required: true,
maxlegth: 32,
},
},
{ timestamps: true }
);
module.exports = mongoose.model("Category", categorySchema);
product model-->
const mongoose = require("mongoose");
const { ObjectId } = mongoose.Schema;
const productSchema = new mongoose.Schema(
{
name: {
type: String,
trim: true,
required: true,
maxlegth: 32,
},
description: {
type: String,
required: true,
maxlegth: 2000,
},
price: {
type: Number,
trim: true,
required: true,
maxlegth: 32,
},
price: {
type: Number,
trim: true,
required: true,
maxlegth: 32,
},
category: {
type: ObjectId,
ref: "Category", //refer to category models
required: true,
},
quantity: {
type: Number,
},
sold: {
type: Number,
default: 0,
},
photo: {
data: Buffer,
contentType: String,
},
shipping: {
required: false,
type: Boolean,
},
},
{ timestamps: true }
);
module.exports = mongoose.model("Product", productSchema);
I have the following code:
var product = await Product.findOne({$and:[
{ name: req.body.name },
{ extraData: [
{brand: req.body.extraData.brand} ,
{quantity: req.body.extraData.quantity},
{typeOfQuantity: req.body.extraData.typeOfQuantity}]}
]});
if (product) res.status(400).send("Product already registered.");
What I would like to do is to check if the given product with these fields already exists in the database so I dont have multiple same object but i have a problem in the nested json object. The code above doesn't work and allows multiple same products to be stored in the array.
The product Scema is:
const productSchema = new mongoose.Schema({
name: {
type: String,
required: true,
minlength: 1,
maxlength: 255
},
extraData: {
type: extraDataSchema,
required: true
}});
const extraDataSchema = new mongoose.Schema({
brand: {
type: String,
required: true,
minlength: 1,
maxlength: 255
},
quantity: {
type: Number,
required: true,
minlength: 1,
maxlength: 10
},
typeOfQuantity: {
type: String,
required: true,
minlength: 1,
maxlength: 255
}
});
I am brand new to MongoDB and to Node JS.
I have got a problem adding a child to a document in Mongo.
The database has a collection cald weddings and in each document is one wedding.
The wedding documents also contain the guests, something like this:
wedding 1
- guest 1
- guest 2
wedding 2
- guest 3
- guest 4
etc.
Now I am having trouble adding guests to the weddings.
Here is my Model:
const Joi = require('joi');
const mongoose = require('mongoose');
const guestSchema = new mongoose.Schema({
name: {
type: String,
required: true,
minlength: 2,
maxlength: 255
},
surname: {
type: String,
required: true,
minlength: 2,
maxlength: 255
},
plz: {
type: String,
minlength: 2,
maxlength: 10
},
confirmed: { type: Boolean, default: false },
type: Number,
questlink_id: Number,
confirmedDate: Date,
hasExtraTable: Boolean
});
const weddingSchema = new mongoose.Schema({
title: {
type: String,
required: true,
minlength: 2,
maxlength: 255
},
nameA: {
type: String,
required: true,
minlength: 2,
maxlength: 255
},
nameB: {
type: String,
required: true,
minlength: 2,
maxlength: 255
},
surnameA: {
type: String,
required: true,
minlength: 2,
maxlength: 255
},
surnameB: {
type: String,
required: true,
minlength: 2,
maxlength: 255
},
location: {
type: String,
required: true,
minlength: 2,
maxlength: 255
},
street: {
type: String,
required: true,
minlength: 2,
maxlength: 50
},
streetnumber: {
type: String,
required: true,
minlength: 1,
maxlength: 50
},
plz: {
type: String,
required: true,
minlength: 2,
maxlength: 10
},
city: {
type: String,
required: true,
minlength: 2,
maxlength: 50
},
country: {
type: String,
required: true,
minlength: 2,
maxlength: 50
},
telefon: {
type: String,
minlength: 5,
maxlength: 50
},
email: {
type: String,
minlength: 5,
maxlength: 255
},
payed: { type: Boolean, default: false },
user_id: {
type: String,
required: true
},
weddingDate: {
type: Date
},
registerUntilDate: {
type: Date
},
tableSize: {
type: Number
},
link: {
type: String,
unique: true,
default: null
},
guest: [ guestSchema ]
});
const Wedding = mongoose.model('wedding',weddingSchema);
function validateWedding(wedding) {
const schema = {
title: Joi.string().min(2).max(255).required(),
nameA: Joi.string().min(5).max(50).required(),
surnameA: Joi.string().min(5).max(50).required(),
nameB: Joi.string().min(5).max(50).required(),
surnameB: Joi.string().min(5).max(50).required(),
location: Joi.string().min(5).max(50).required(),
street: Joi.string().min(5).max(50).required(),
streetnumber: Joi.string().min(5).max(50).required(),
city: Joi.string().min(5).max(50).required(),
plz: Joi.string().min(5).max(50).required(),
country: Joi.string().min(5).max(50).required(),
};
return Joi.validate(wedding, schema);
}
function validateGuest(guest) {
const schema = {
name: Joi.string().min(5).max(50).required(),
surname: Joi.string().min(5).max(50).required(),
plz: Joi.string().min(5).max(50).required()
};
return Joi.validate(guest, schema);
}
exports.guestSchema = guestSchema;
exports.weddingSchema = weddingSchema;
exports.Wedding = Wedding;
exports.validateWedding = validateWedding;
exports.validateGuest = validateGuest;
Here is my Router, or at least the important parts:
const auth = require('../middleware/auth');
const {Wedding, validateWedding, validateGuest, guestSchema} = require('../models/wedding');
const {User} = require('../models/user');
const _ = require('lodash');
const mongoose = require('mongoose');
const express = require('express');
const router = express.Router();
router.get('/:id/guests', auth, async (req, res) => {
const weddings = await Wedding.findById(req.params.id);
if(weddings.user_id != req.user._id)
res.status(400).send('This is not your wedding');
res.send(weddings.guest);
});
router.post('/:id/guests', auth, async (req, res) => {
const { error } = validateGuest(req.body);
if (error) return res.status(400).send(error.details[0].message);
const weddings_1 = await Wedding.findById(req.params.id);
if(weddings_1.user_id != req.user._id)
res.status(400).send('This is not your wedding');
const guest = mongoose.model('Guest',guestSchema);
guest.name = req.body.name;
guest.surname = req.body.surname;
guest.plz = req.body.plz;
let weddings = await Wedding.findByIdAndUpdate(req.params.id,{
guest: [ {
name : req.body.name,
surname: req.body.surname,
plz: req.body.plz
} ]
});
// weddings.guest.push(guest);
res.send(weddings);
});
module.exports = router;
I have tried to push the data into the DB and I have tried to update the whole document.
If anyone has any suggestions, thanks!
I think the problem is that you are not creating the new guest and not saving the Wedding either:
(thanks #ykit9 for the correction)
const Guest = mongoose.model('Guest', guestSchema);
const newGuest = new Guest({
name : req.body.name,
surname: req.body.surname,
plz: req.body.plz
});
newGuest.save();
Wedding.findOne({_id: req.params.id}, (err, foundWedding)=>{
foundWedding.guest.push(newGuest);
foundWedding.save();
res.send(foundWedding);
});
If you need further information: Constructing Documents in Mongoose - Documentation