Aggregate not giving any results - javascript

I'm attempting to do partial search in my mongoose database for city names.
This is how I have Trips defined.
const mongoose = require('mongoose');
const TravelSchema = new mongoose.Schema({
creator: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
},
numPeople: {
type: Number,
required: true
},
startDate: {
type: Date,
required: true
},
endDate: {
type: Date,
required: true
},
destination: [{
city: {type: String, required :true},
state: {type: String, required:true }
}],
budget :[{
travelCost: {type: Number},
foodCost: {type: Number},
lodgingCost: {type: Number},
miscellaneousCost: {type: Number}
}]
});
module.exports = mongoose.model('Trips', TravelSchema);
No matter what I try, aggregate is not giving me any results (not even an error) and I have no idea why.
This is what my search looks like. Ideally the Trip.aggregate I have commented out would work but even the simple one is not giving any output
const router = require('express').Router();
const mongoose = require('mongoose');
let Trip = require('../models/Trips');
/*Trip.aggregate([
//{ $project : {'destination' : 1}},
{ $unwind : "$destination"},
/*{
$match: {
'destination.city' :{
"$regex" : new RegExp(req.body.city), "$options" : "i"
}
}
}
]),function(err,results){
console.log(err);
console.log(results);
console.log("Im in here2");
}*/
router.post('/', (req, res, next) => {
console.log("Im in here");
Trip.aggregate([{
$match: {
numPeople: {
$gt: 0,
$lt: 10
}
}
}]),
function(err, results) {
if (err)
console.log(err);
console.log(results);
}
})
module.exports = router;
I know I have things in the database with those fields and I should get a result for the age.
Here is some of the data in my mongodb.
MongoSC

Related

How can i create a module for a course website using mongoDB and node.js

/I want to create a module section for a course website for which I will need a lesson schema as well so How can I design lesson schema , module schema , and course schema so they
work just how they are needed to workCurrently I am doing this/
import mongoose from 'mongoose'
const LessonSchema = new mongoose.Schema({
title: String,
content: String,
resource_url: String
})
const ModuleSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
lessons: [LessonSchema]
})
export const Module = mongoose.model('Module', ModuleSchema);
const CourseSchema = new mongoose.Schema({
name: {
type: String,
trim: true,
required: 'Name is required'
},
price: {
type: String,
trim: true,
required: true
},
image: {
data: Buffer,
contentType: String
},
intro: {
type: String,
required :true
},
description: {
type: String,
trim: true
},
category: {
type: String,
required: 'Category is required'
},
updated: Date,
created: {
type: Date,
default: Date.now
},
instructor: {type: mongoose.Schema.ObjectId, ref: 'User'},
published: {
type: Boolean,
default: false
},
modules: [ModuleSchema]
})
export default mongoose.model('Course', CourseSchema)
Above was the schema and this is logic
const newLesson = async (req, res) => {
try {
let lesson = req.body.lesson
let course = await Course.find({modules: {_id: req.params.moduleId}})
console.log(course)
} catch (err) {
return res.status(400).json({
error: errorHandler.getErrorMessage(err)
})
}
}
const newModule = async (req, res) => {
try {
let lesson = req.body.lesson
let result = await Course.findByIdAndUpdate(req.course._id, {$push: {modules: {name: req.body.name, lessons: lesson}}, updated: Date.now()}, {new: true})
.populate('instructor', '_id name')
.exec()
res.json(result)
} catch (err) {
return res.status(400).json({
error: errorHandler.getErrorMessage(err)
})
}
}
**I have been brainstorming this from a while and cant get through it do you know how can I shape the schema and logic so that I can push lessons in module and then module in course schema ? **

Mongoose $or condition for nested array

There are my schemas
//ProjectModel
const ProjectSchema: Schema = new Schema(
owner: { type: Schema.Types.ObjectId, ref: "User" },
users: [{type: Schema.Types.ObjectId, ref: "ProjectUser", unique: true }]
);
//Project User model
const ProjectUserSchema = new Schema(
{
user: { type: Schema.Types.ObjectId, ref: "User", require: true },
role: {
type: String,
default: 'basic',
enum: ["basic", "projectuser", "moderator", "admin"]
},
project: { type: Schema.Types.ObjectId, ref: "Project", require: true },
},
{
timestamps: true,
usePushEach: true,
}
);
The User model has common fields like password, name, etc.
I want to find User of a ProjectModel either among the owner (UserSchema) or among users (ProjectUserSchema)
ProjectModel.findOne()
.or([{ owner: req.params.user }, { "users.user": req.params.user }])
.then(project => {
res.json(project);
});
But it returns null. And condition .or([{ owner: req.params.user }, { "users._id": "PROJECT USER ID" }]) doesn't work either.
What should I do?
You need to convert the incoming req.params.user from string to ObjectId. Try this:
const mongoose = require('mongoose');
const getProjectByUser = (req, res) => {
let userId = mongoose.Types.ObjectId(req.params.user);
ProjectModel
.findOne({
$or: [
{ "owner": userId },
{ "users": userId }
]
})
.then(project => {
res.json(project);
})
.catch(e => {
res.json({ error: "Error!" });
});
}

Check if a key in array of objects in Javascript?

I try to check if a value is in array's objects. After that I push the object is the value is not in the array. How can I do this ?
router.post('/save', (req, res) => {
let userId = req.user.id
let dataPushSave = req.body.idSave
let dataPushSaveObj = {idSave: dataPushSave}
User.findById(userId, (err, user) => {
if (user.favorites.idSave !== dataPushSave) {
user.favorites.push(dataPushSaveObj)
user.save()
}
})
My mongoose model:
const User = new Schema({
firstName: {
type: String,
required: true
},
favorites: [{
_id: Object,
idSave: String
}]
});
const User = new Schema({
firstName: {
type: String,
required: true
},
favorites: [{
_id: Object,
idSave: String
}]
});
From the above schema, remove _id: Object from favorites.
I would recommend below schema
const User = new Schema({
firstName: {
type: String,
required: true
},
favorites: {
type: [new Schema({
idSave: { type: String },
}, { _id: false })]
}
});
Then use $addToSet operator to make sure there are no duplicates in the favorites array.
let user;
User.findByIdAndUpdate(
userId,
{ $addToSet: { favorites: dataPushSaveObj } },
{ new: true }, // this option will make sure you get the new updated docc
(err, doc) => {
if (err) console.error(err);
user = doc;
}
);

Mongoose schema : SubDocument field only unique per Document

I have a little question. I have a User schema which contains a table fields redirecting to the Table schema.
A Table element can contain a name, I want this name to be unique per User but not between User.
Example:
User1 -> Table1.name: "foo"
User2 -> Table1.name: "foo"
But this User1 -> Table2.name: "foo" cannot be possible.
This is the User Schema:
var UserSchema = new mongoose.Schema({
username: { type: String, required: true, index: {
unique: true } },
email: { type: String, required: true, index: {unique: true } },
password: { type: String, required: true },
tables: [{ type: Schema.Types.ObjectId, ref: 'Table' }],
resetPasswordToken: String,
resetPasswordExpires: Date,
uuid: String,
});
This is the Table schema:
var TableSchema = Schema({
name: { type: String, required: true, index: { unique: true }},
logos: [{ type: Schema.Types.ObjectId, ref: 'Logo'}],
});
And this is where I do the queries:
app.post('/newTab', function(req, res){
var use = req.user.username;
var newTab = new Table({
name: req.body.name,
});
newTab.save(function(err, docs){
if (err)
{
console.error(err);
res.writeHead(500);
res.end();
}
else
{
User.findOne({username: req.user.username}, function(err, docs) {
if(err) {throw (err);}
else
{
docs.tables.push(newTab);
docs.save(function(err, docs){
if (err) return console.error(err);
res.writeHead(200);
res.end(userId);
});
}
});
}
});
For now, I cannot add the same table name for two different User ..
I also tried something with sparse index but can't figure how it works

Mongoose populate not populating

I am trying to populate my users car inventory. All the cars have a userId attached to them when they are created but when I go to populate the inventory it doesn't work and I get no errors.
Here are my models:
User.js
let UserSchema = mongoose.Schema({
username: {
type: String,
required: true,
unique: true
},
password: {
type: String,
required: true
},
inventory: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Car' }]
});
let User = mongoose.model('User', UserSchema);
models.User = User;
Cars.js
let CarSchema = mongoose.Schema({
userId: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
},
make: {
type: String,
required: true
},
model: {
type: String,
required: true
},
year: {
type: String
}
});
let Car = mongoose.model('Car', CarSchema);
models.Car = Car;
Here is the populate code:
router.route('/users/:user/inventory').get((req, res) => {
User.findById(userId)
.populate('inventory')
.exec((err, user) => {
if (err) {
console.log("ERRROORRR " + err)
return res.send(err);
}
console.log('Populate ' + user)
res.status(200).json({message: 'Returned User', data: user});
});
});
};
This is what a car object looks like in the database:
{
"_id": ObjectId("5759c00d9928cb581b5424d0"),
"make": "dasda",
"model": "dafsd",
"year": "asdfa",
"userId": ObjectId("575848d8d11e03f611b812cf"),
"__v": 0
}
Any advice would be great! Thanks!
Populate in Mongoose currently only works with _id's, though there's a long-standing issue to change this. You'll need to make sure your Car model has an _id field and that the inventory field in User is an array of these _id's.
let CarSchema = new mongoose.Schema(); //implicit _id field - created by mongo
// Car { _id: 'somerandomstring' }
let UserSchema = new mongoose.Schema({
inventory: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'Car'
}]
});
// User { inventory: ['somerandomstring'] }
User.populate('inventory')

Categories