MongoDB relation between two collections by ID with the Express - node.js

I am facing a problem while making a relation between two collections (I am using MEAN stack)
I have two collections: Books and Authors
In frontend I want to make a CRUD menu, where I add a new book in the table and then from there i insert a few data about book and then I choose author from the dropdown menu (fetchin data from Authors collection)
So at the end my Book collection needs to have a few data about the book and then inside the object i need an array of data about those author.
Book schema:
const BookSchema = new mongoose.Schema({
owner: { type: String, required: true },
pagesNo: { type: String, required: true },
releaseDate: { type: String, required: true },
country: { type: String, required: true },
authorID: { type: String, required: true }, <-- HERE I NEED DATA ABOUT AUTHOR
});
Author schema:
const AuthorSchema = new mongoose.Schema({
name: { type: String, required: true },
surname: { type: String, required: true },
dateOfBirth: { type: String, required: true },
countryOfBirth: { type: String, required: true },
});
Book route: book.ts
router.get("/", async (req, res) => {
try {
const books= await Book.find();
let Author = await Author.find({
books: { $elemMatch: { _id: books.bookID } },
});
res.status(200).json(books);
} catch (err) {
res.status(404).json({ success: false, msg: "Booknot found" });
}
});
The problem is somewhere inside the find() function.. Is it even a good practice? I want that it can handle a lot of data.
Thanks to everyone!
Greetings.

Your Book schema would be like this:
const MongooseSchema = new mongoose.Schema({
owner: {
type: String,
required: true,
},
pagesNo: {
type: String,
required: true,
},
releaseDate: {
type: String,
required: true,
},
country: {
type: String,
required: true,
},
authorId: {
type: mongoose.Schema.ObjectId,
ref: 'User',
required: true,
},
});
And your Author Schema would remain the same (in order to link both schemas).
Your route would be like this (if you want to search all books along with their author names):
router.get('/', async (req, res) => {
try {
const books = await Book.find().populate('authorId');
res.status(200).json(books);
} catch (err) {
res.status(404).json({ success: false, msg: 'Booknot found' });
}
});
And in case you want to search for books with a specific author id then your route would be like this:
router.get('/', async (req, res) => {
try {
const books = await Book.find({ authorId }).populate('authorId');
res.status(200).json(books);
} catch (err) {
res.status(404).json({ success: false, msg: 'Booknot found' });
}
});

AuthorID should be type ObjectId, not string.
To join data from other table, you have to use an aggregate with a lookup.
let author = await Author.aggregate([
{
$lookup:
{
from: "books",
localField: "_id",
foreignField: "authorID",
as: "books"
}
}
]);

Related

How to populate data in dynamoose

I'm building an API where a user can make a publication to be displayed on a thread. I'm trying to make the author data to be seen with the publication. This way the author data could be get like
console.log( publication.author.completeName )
When saving publication, I save the author field with the value of the user id posting the publication.
Then I'm trying to populate the data like shown here
This is my User model
const dynamoose = require("dynamoose");
const { v4: uuidv4 } = require('uuid');
const userSchema = new dynamoose.Schema(
{
id: {
type: String,
hashKey: true,
default: () => uuidv4(),
},
email: {
type: String,
required: true
},
completeName: {
type: String,
},
pseudo: {
type: String, // Should make check on create and edit to ensure unicity of this column
},
gender: {
type: String,
enum: ['male', 'female', 'other']
},
speciality: {
type: String
},
address: {
type: String,
},
phoneNumber: {
type: String,
}
},
{ timestamps: true }
);
module.exports = dynamoose.model("User", userSchema);
and this is my publication model:
const dynamoose = require("dynamoose");
const { v4: uuidv4 } = require('uuid');
const publicationSchema = new dynamoose.Schema(
{
id: {
type: String,
hashKey: true,
default: () => uuidv4(),
},
photo: {
type: Array,
schema: [String],
default: []
},
description: {
type: String,
required: true
},
anatomies: {
type: Array,
schema: [String],
required: true,
},
specialities: {
type: Array,
schema: [String],
required: true,
},
groupId: {
type: String,
},
author: {
type: String
}
},
{ timestamps: true }
);
module.exports = dynamoose.model("Publication", publicationSchema);
I'm trying to populate the author field when getting all the data like this:
exports.listPublication = async (req, res, next) => {
try {
Publication
.scan()
.exec()
.then( async function (data) {
return Promise.all( data.map(function(pub){
return pub.populate({
path: 'author',
model: 'User'
});
}))
})
.then((data) => {
success(res, { data: data });
})
.catch((err) => {
throw new HttpException(err.message);
});
} catch (err) {
error(next, res, err);
}
}
but the author field is not populated, it only display the value of the author field, which is the string value of the author id.
Help please, I can't figure what I'm doing wrong

Mongoose How to sort .populate field

I'm work with an user/articles profile system. I have been using the .populate() to render the posts but I cannot get the articles sorted by the date they were created.
I am using the createdAt variable as the main way of ordering the posts displayed.
For reference:
router.get('/:id', async (req, res) => {
const user = await User.findById(req.params.id, function(error) {
if(error) {
req.flash("error", "something went wrong")
res.redirect("/");
}
}).populate('articles')
res.render('users/show',{
user: user
});
and the article.js:
const ArticleSchema = new mongoose.Schema({
title: {
type: String,
required: true
},
author: {
type: String
},
markdown: {
type: String,
required: true
},
createdAt: {
type: Date,
default: Date.now
},
slug: {
type: String,
required: true,
unique: true
},
sanitizedHtml: {
type: String,
required: true
},
img: {
type: String
},
type:{
type: String
},
user : { type: Schema.Types.ObjectId, ref: 'User' },
}, {timestamps: true});
In advance thank you all for the help.
There is a property called options in populate,
.populate({
path: 'articles',
options: { sort: { createdAt: -1 } }
})

node.js why dose mongodb throw casting error

//this error appear
{
"error": {
"message": "Cast to ObjectId failed for value \"events\" at path \"_id\" for model \"user\"",
"name": "CastError",
"stringValue": "\"events\"",
"kind": "ObjectId",
"value": "events",
"path": "_id"
}
}
//when execute this code
exports.get_all_events = (req, res, next) => {
Event.find({})
.populate("creator","name _id",user) // must define model reference
.then(result => {
console.log(result);
res.status(200).json({ result });
}).catch(err => {
console.log(err);
res.status(500).json({ error: err });
});
}
Event schema
const mongoose = require('mongoose');
// creat event schema
const eventSchema = mongoose.Schema({
name: {
type: String,
required: [true, 'name is required']
},
location: {
type: String,
required: [true, 'location is required']
},
date: {
type: String,
required: [true, 'data is required']
},
description: {
type: String,
required: [true, 'description is required']
},
creator: {
_id: {
type: mongoose.Schema.Types.ObjectId,
ref: "users"
}
}
});
module.exports = mongoose.model("events", eventSchema);
Userschema
const mongoose = require('mongoose');
const userSchema = mongoose.Schema({
email: {
type: String,
required: true,
unique: true,
match: /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/
},
password: {
type: String,
required: true
},
name: {
type: String,
required: true
},
post: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "posts"
}
],
event: [
{
type: mongoose.Schema.Types.ObjectId,
// it point to collection
ref: "events"
}
]
});
module.exports = mongoose.model('users', userSchema);
it works great adding event to database and get single event it work but when i get all events from database throw casting error and can't make any updating on exist event
I think you are populating the events document little bit wrong.
Try this:
Event.find({})
.populate("creator._id","name _id")
.then(result => {
console.log(result);
res.status(200).json({ result });
}).catch(err => {
console.log(err);
res.status(500).json({ error: err });
});
I dont think you need any third argument in the .populate() function, You have already defined in your schema, where it should be populated from:
//look here, you have already defined it in your schema
creator: {
_id: {
type: mongoose.Schema.Types.ObjectId,
ref: "users" //this says which collection it should be populated from
}
}
I hope it helps you out.

Mongoose - search a new collection based on the first collection result

I have two collections as follows :
This is my vehicle schema
const VehicleSchema = new schema({
user: {
type: schema.Types.ObjectId,
ref: "users"
},
name: {
type: String,
required: true
},
brand: {
type: String,
required: true
},
plate: {
type: String,
required: true
},
IMEI: {
type: String,
required: true
}
});
This is my Trip schema
const TripSchema = new schema({
date: {
type: Date,
default: Date.now
},
IMEI: String,
data: [
{
lat: String,
lon: String
}
]
});
Trip and Vehicle schemas share the the key IMEI, so when the user is logged in I wanna grab the trips based on the IMEI number, what is the most efficient way to approach this problem ? here is a look at my router
router.get(
"/",
passport.authenticate("jwt", { session: false }),
(req, res) => {
Vehicles.find({ user: req.user.id }).then(vehicles => {
if (!vehicles) {
return res.json({ error: "you do not have any vehicles yet" });
}
Trips.find().then(trips => {
// ??
});
});
}
);
You can simply do a $lookup and do a left join on trips with vehicles:
db.vechicles.aggregate([
{
$lookup:
{
from: "trips",
localField: "IMEI",
foreignField: "IMEI",
as: "trips"
}
}
])
This should get you what you want in one call.
Note this is available in mongodb versions 3.2+

Nodejs:Array data not added in mongodb

This is my model profile.js
var mongoose = require('mongoose');
const ProfileSchema = mongoose.Schema({
educationinfo: [{
universityname:
{
type: String,
required: true
},
degree:
{
type: String,
required: true
},
coursecompletionyear:
{
type: String,
required: true
},
collegename:
{
type: String,
required: true
},
specialization:
{
type: String,
required: true
},
marks:
{
type: String,
required: true
},
courselevel:
{
type: String,
required: true
}
}]
});
const Profile = module.exports = mongoose.model('Profile', ProfileSchema);
This is my route.js post function
router.post('/addprofiledetails', function(req, res, next) {
let newProfile = new Profile({
$educationinfo:[{
universityname:req.body.universityname,
degree:req.body.degree
}]
});
newProfile.save((err, profile) => {
if (err) {
res.json({ msg: 'Failded to add profiledetails' });
} else {
res.json({ msg: 'successfully add profile details' });
}
});
});
I got success msg in post function but the data not added in mongodb. i don't know where i did mistake .please help me.
In mongoDB I got data like,
{
"educationinfo": [],
"_id": "5bed14b93a107411a0334530",
"__v": 0
}
I want details inside educationinfo, please help.
You need to change schema definition and query.
1.remove required from schema Or apply required to those field that you must provide value.
educationinfo: [{
universityname:
{
type: String,
// required: true
},
degree:
{
type: String,
//required: true
},
coursecompletionyear:
{
type: String,
// required: true
},
collegename:
{
type: String,
// required: true
},
specialization:
{
type: String,
//required: true
},
marks:
{
type: String,
// required: true
},
courselevel:
{
type: String,
// required: true
}
}]
2.change $educationinfo with educationinfo
educationinfo:[{
universityname:req.body.universityname,
degree:req.body.degree
}]
Since you marked the properties of educationinfo as required, you need to provide them when you create an instance of Profile. If you don't want to do that you need to remove the required property from those properties that you won't be supplying on instance creation like below:
const mongoose = require('mongoose');
const ProfileSchema = mongoose.Schema({
educationinfo: [{
universityname:
{
type: String,
required: true
},
degree:
{
type: String,
required: true
},
coursecompletionyear:
{
type: String
},
collegename:
{
type: String
},
specialization:
{
type: String
},
marks:
{
type: String
},
courselevel:
{
type: String
}
}]
});
const Profile = module.exports = mongoose.model('Profile', ProfileSchema);
After making those changes, you need to make one more change in your POST route, change $educationinfo to educationinfo
router.post('/addprofiledetails', function(req, res, next) {
const newProfile = new Profile({
educationinfo:[{
universityname: req.body.universityname,
degree: req.body.degree
}]
});
newProfile.save((err, profile) => {
if (err) {
res.json({ msg: 'Failded to add profiledetails' });
} else {
res.json({ msg: 'successfully add profile details' });
}
});
});
The data you insert is incomplete.
The properties in your schema marked as required: true need to be inserted aswell. Because you do not meet the schema requirements, it is failing.

Resources