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
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?
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>
};
so my code is that:
router.put("/add-task/:id", auth, boardAuth, async (req, res) => {
const listId = req.params.id;
try {
const board = await Board.findOne({ _id: req.board._id });
if (!board) return res.status(404).send("no such board");
const list = await List.findOne({ _id: listId });
if (!list) return res.status(404).send("List not found");
const task = new Task({
text: req.body.text,
});
list.cards.push(task);
board.boardLists.forEach((list) => {
if (listId.toString() === list._id.toString()) {
list.cards.push(task);
} else {
console.log('no task');
}
});
await board.save();
await list.save();
res.send(board);
} catch (err) {
console.log(err);
}
});
i want to save task (card) inside the board object.
my res is that:
"boardMembers": [
"5f326c2e8b906103642af93b"
],
"boardLists": [
{
"cards": [
{
"_id": "5f63147c14ba4d4464e263ea",
"text": "two"
}
],
"_id": "5f622ca82e6edf1eb8dab7b7",
"title": "list number one",
"__v": 0
}
],
"_id": "5f622c702e6edf1eb8dab7b6",
"boardName": "board one",
"boardPassword": "123456",
"boardCreator": "5f326c2e8b906103642af93b",
"g_createdAt": "2020-09-16T15:17:04.012Z",
"__v": 2
the problem is when i refresh or sending request again the array of cards is empty again. its not saving the last doc ("two") i added. what i am doing worng here?
update - schema of board
this is the Boardschema
const boardSchema = new mongoose.Schema({
boardName: {
type: String,
required: true,
maxLength: 255,
minLength: 2,
},
boardPassword: {
type: String,
required: true,
minlength: 6,
maxlength: 255,
},
g_createdAt: { type: Date, default: Date.now },
boardCreator: { type: mongoose.Schema.Types.ObjectId, ref: "User" },
boardMembers: Array,
boardLists: Array,
});
const Board = mongoose.model("Board", boardSchema);
this is the List schema
const listSchema = new mongoose.Schema({
title: {
type: String,
required: true,
maxLength: 255,
minLength: 1,
},
cards: Array,
});
const List = mongoose.model("List", listSchema);
this is the Task schema:
const taskSchema = new mongoose.Schema({
text: {
type: String,
required: true,
maxLength: 1024,
minLength: 2,
},
taskOf: { type: mongoose.Schema.Types.ObjectId, ref: "List" },
});
Cascade your reference fields in the opposite direction:
const boardSchema = new mongoose.Schema({
boardName: {
type: String,
required: true,
maxLength: 255,
minLength: 2,
},
boardPassword: {
type: String,
required: true,
minlength: 6,
maxlength: 255,
},
g_createdAt: { type: Date, default: Date.now },
boardCreator: { type: mongoose.Schema.Types.ObjectId, ref: "User" },
boardMembers: Array,
boardLists: [{ type: mongoose.Schema.Types.ObjectId, ref: "lists" }],
});
const listSchema = new mongoose.Schema({
title: {
type: String,
required: true,
maxLength: 255,
minLength: 1,
},
cards: [{ type: mongoose.Schema.Types.ObjectId, ref: "tasks" }],
});
const taskSchema = new mongoose.Schema({
text: {
type: String,
required: true,
maxLength: 1024,
minLength: 2,
},
});
const List = mongoose.model("lists", listSchema);
const Board = mongoose.model("boards", boardSchema);
const Task = mongoose.model("tasks", boardSchema);
See if data gets persisted following this logic
So here is my User.model.js file:
const mongoose = require('mongoose');
const jwt = require('jsonwebtoken');
const crypto = require('crypto');
const UserSchema = new mongoose.Schema({
username: {
required: true,
type: String,
minlength: 4,
maxlength: 128,
trim: true
},
displayname: {
required: true,
type: String,
minlength: 4,
maxlength: 128,
trim: true
},
email: {
required: true,
type: String,
minlength: 8,
maxlength: 256,
},
password: {
required: true,
type: String,
minlength: 8
},
sessions: [
{
token: {
type: String,
required: true
},
expiresAt: {
type: Number,
required: true
}
}
]
});
// Some irrelevant functions
const User = mongoose.model('User', UserSchema);
module.exports = User;
So what i would like to do is find a User by using only the session token but it's proving a little difficult because there can be multiple objects in the session array for each User, all of which i want to search through.
You can query like this
const user = await User.findOne({"sessions.token": session_token})
or
const user = await User.findOne({sessions: {$elemMatch: { token: session_token }}})
For more info, you can refer documentation.
https://docs.mongodb.com/manual/tutorial/query-array-of-documents/
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
}
});