Mongoose find documents where field = req.body.user - node.js

I have a user schema and a post schema, wherein a user has many posts. I would like to return all posts that the user has on a route called '/post/dashboard'.
Here is my schemas:
let UserSchema = new Schema({
username: {
type: String,
required: true,
unique: true,
},
password: {
type: String,
default: null,
},
profile_pic: {
type: String,
default: '/img/profilepic.png',
},
posts: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Post'
}
})
let PostSchema = new Schema({
title: {
type: String,
},
description: {
type: String,
}
original_poster: {
type: Schema.Types.ObjectId,
ref: 'User',
required: true
},
tags: {
type: [String]
}
})
So, for example something like:
app.get('/', (req,res) => {
Post.find({ original_poster: req.session.user }).then((posts) =>{
res.send(JSON.stringify(posts));
}) //where req.session.user is an id (the logged in user's object id or _id)
})
Essentially in sql syntax it might be something like:
SELECT * FROM POSTS WHERE ORIGINAL_POSTER = <req.session.user>
What is the proper way to return all posts by the req.session.user?

It seems that original_poster field represent a reference to User's model, If req.session.user is stored as a string you have to cast it to objectID:
const mongoose = require('mongoose');
...
let userId = mongoose.Types.ObjectId(req.session.user);
Post.find({ original_poster: userId }).then((posts) => {
res.send(JSON.stringify(posts));
});

Related

Implementing text search with Mongoose

I want to implement text search on my app, and find documents where the field login matches the searched term,
I did the code below and I have no errors but the result in the route is always an empty array, there must be an error somewhere
Model
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const UserSchema = new Schema({
created_at: {
type: String,
required: true,
},
description: {
type: String,
required: true,
},
display_name: {
type: String,
required: true,
index: true,
},
login: {
type: String,
required: true,
index: true,
},
});
UserSchema.index({ login: "text", display_name: "text" });
User = mongoose.model("users", UserSchema);
User.createIndexes();
module.exports = User;
Route
router.post("/users", async function (req, res) {
const { search } = req.body;
const users = await User.find({ $text: { $search: search } });
res.send(users);
});

How to access nested data which is a reference data in an array in mongoose?

So I have this nested data object which is also a reference data. When I try to access it using populate it is showing only the id. I do not want only the id. I also want the details to come along. Can someone please help me on this?
This is the EmployeesDetailsSchema which have this employeesinfo property with a reference in it. Now the designation and speciality property as you can see in the image is coming only in ids and not the full details i want the full the details of these two as well as the other fields also.
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const EmployeesDetailsSchema = new Schema({
employeesinfo: {
type: mongoose.Schema.Types.ObjectId,
ref: "employees"
},
workingdays: Number,
fathersname: String,
pan: String,
joiningdate: Date,
gender: String,
pfno: String,
esino: String,
branchname: String,
department: String,
paymode: String,
bankname: String,
acno: String,
ifscno: String,
//Earnings
basicsalary: Number,
extra: Number,
totalE: Number,
//Days
fixeddays: Number,
presentdays: Number,
absentdays: Number,
leavedays: Number,
holidays: Number,
//Deductions
pf: Number,
esi: Number,
professionaltax: Number,
advance: Number,
absentdeductions: Number,
leavedeductions: Number,
totalD: Number,
//Net pay Details
netpay: Number,
inwords: String,
name: String,
date: {
type: Date,
default: Date.now
}
});
module.exports = EmpDetails = mongoose.model(
"empdetails",
EmployeesDetailsSchema
);
This is the EmployeesSchema which is reference in the employeesinfo property of the EmployeesDetailsSchema
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const EmployeesSchema = new Schema({
name: { type: String },
email: { type: String },
speciality: {
type: mongoose.Schema.Types.ObjectId,
ref: "speciality"
},
contactno: { type: Number },
designation: {
type: mongoose.Schema.Types.ObjectId,
ref: "designation"
},
alternatecontactno: { type: Number },
address: { type: String },
employeeImage: { type: String },
imageName: { type: String },
date: { type: Date, default: Date.now() }
});
module.exports = Employees = mongoose.model("employees", EmployeesSchema);
And these are the two models which is being reference in the EmployeesSchema
//Speciality Type Schema
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const SpecialitySchema = new Schema({
speciality: {
type: String
},
description: {
type: String
}
});
module.exports = Speciality = mongoose.model("speciality", SpecialitySchema);
//Designation Type Schema
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const DesignationSchema = new Schema({
designation: {
type: String
},
description: {
type: String
}
});
module.exports = Designation = mongoose.model("designation", DesignationSchema);
And this is the get route
router.get("/", (req, res) => {
EmpDet.find()
.populate({
path: "employeesinfo"
})
.then(empdet => res.json(empdet))
.catch(err =>
res.status(400).json({ msg: "Error in finding Employees Details" })
);
});
Populate usually returns the entire referred document if there is no specific options set. It can be used like this:
const story = await Story.findOne({ title: 'Some Titel' }).populate('authors');
See full documentation and further samples:
https://mongoosejs.com/docs/populate.html
Try this:
EmpDet.find()
.populate({
path: "employeesinfo",
populate: [
{ path: 'speciality' },
{ path: 'designation' }
]
})
.then(empdet => res.json(empdet))
.catch(err =>
res.status(400).json({ msg: "Error in finding Employees Details" })
);
Also, please have a look at the documentation too as mentioned by Simon.
https://mongoosejs.com/docs/populate.html

E11000 duplicate key error with MongoDB/Mongoose

I have a user model schema, a work model schema, and a critique model schema. The relationship between these schema's is a user can submit many works (like blog posts), and can comment/review (which we call critiques) other people's posts (works).
So when a user submits a critique (think of it like a review), this is my post route. I find the work by the id, then create a new critique model object, and pass that to the .create() mongoose function. All goes seemingly well until I hit the foundWork.critiques.push(createdCritique) line. the console log errors out saying:
BulkWriteError: E11000 duplicate key error collection: zapper.critiques index: username_1 dup key: { : null }
Obviously, it is saying that there are two username keys in the objects and they're conflicting with each other, but I'm not familiar enough with this to find the root of the issue and fix it in the mongoose models. The models are below. If anyone could help, that'd be greatly appreciated.
// post route for getting the review
router.post('/:id', isLoggedIn, function(req, res) {
Work.findById(req.params.id, function(err, foundWork) {
if (err) {
console.log(err);
} else {
// create a new critique
var newCritique = new Critique ({
reviewerName: {
id: req.user._id,
username: req.user.username
},
work: {
id: foundWork._id,
title: foundWork.title
},
critique : req.body.critique,
date: Date.now(),
rating: 0
});
// save new critique to db
Critique.create(newCritique, function(err, createdCritique) {
if (err) {
console.log(err)
} else {
console.log("Created critique is ");
console.log(createdCritique);
// push the new critique into array of critiques of the work
foundWork.critiques.push(createdCritique);
// save to db
foundWork.save();
}
});
}
});
User model:
var mongoose = require('mongoose');
var passportLocalMongoose = require('passport-local-mongoose');
var UserSchema = new mongoose.Schema({
firstname: String,
lastname: String,
username: String,
password: String,
email: String,
zip: String,
bio: {
type: String,
default: ''
},
influences: {
type: String,
default: ''
},
favBooks: {
type: String,
default: ''
},
notWriting: {
type: String,
default: ''
},
favHero: {
type: String,
default: ''
},
favVillain: {
type: String,
default: ''
},
works: [
{
type: mongoose.Schema.Types.ObjectId,
ref: 'Work'
}
],
critiques: [
{
type: mongoose.Schema.Types.ObjectId,
ref: 'Critique'
}
],
friends: [
{
friendId: String,
friendName : String,
friendPic: String
}
],
friendRequests: [
{
sendingFriendId: String,
sendingFriendName : String,
sendingFriendPic: String
}
],
createdDate: {
type: Date,
default: Date.now
},
lastLogin: {
type: Date,
default: Date.now
}
});
UserSchema.plugin(passportLocalMongoose);
module.exports = mongoose.model("User", UserSchema);
Work model:
var mongoose = require('mongoose');
var WorkSchema = new mongoose.Schema({
title: String,
genre: String,
workType: String,
length: Number,
ageRange: String,
author: {
id: {
type: mongoose.Schema.Types.ObjectId,
ref: "User"
},
username: String
},
manuscriptText: String,
critiques: [
{
id: {
type: mongoose.Schema.Types.ObjectId,
ref: "Critique"
}
}
],
ratingNumber: [Number],
ratingSum: {
type: Number,
default: 0
},
date: {
type: Date,
default: Date.now
},
isPublic: {
type: Boolean,
default: true
}
});
module.exports = mongoose.model("Work", WorkSchema);
Critique model:
var mongoose = require('mongoose');
var passportLocalMongoose = require('passport-local-mongoose');
var CritiqueSchema = new mongoose.Schema({
reviewerName: {
id: {
type: mongoose.Schema.Types.ObjectId,
ref: "User"
},
username: String
},
work: {
id: {
type: mongoose.Schema.Types.ObjectId,
ref: "Work"
},
title: String
},
critique: String,
date: {
type: Date,
default: Date.now
},
rating: [Number]
});
CritiqueSchema.plugin(passportLocalMongoose);
module.exports = mongoose.model("Critique", CritiqueSchema);
When you create a unique index in MongoDB, the default behavior is that it will index null values also.
This means if you have a document in your collection with a username of null, you can not add another one with a username of null.
What you need is a sparse index which only indexes actual values (and ignores documents with null for that field).
Check this link It shows how to create a sparse index vs "normal" one in mongoose (index: true, vs spare: true). Most of the time you would want sparse indexes.

Mongoose query compare ObjectId

I'm trying to fetch some documents from my db. In each document, there is a field called 'owner' which is an ObjectId of a user. I want to fetch all of the documents of a specific user. I have the user id and when I'm trying to do something like this:
exports.getBoxes = function(req, res) {
const { user } = res.locals;
const query = db.Box.find();
query.where('owner').equals(user._id);
query.exec(function(err, boxes) {
console.log(boxes);
});
}
I get an empty array. I saw in my db and there are many boxes that corresponds to this query. What's wrong with it?
UPDATE
Here is my schema:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const timestamps = require('mongoose-timestamps');
const BoxSchema = new Schema({
description: {
type: String,
trim: true
},
producer: {
type: String,
trim: true
},
cycle: {
type: String,
trim: true
},
owner: {
type: Schema.ObjectId,
ref: 'Supplier'
},
event: {
type: Schema.ObjectId,
ref: 'Event'
},
type: {
type: String,
enum: []
},
creditTerms: {
type: String,
enum: ['Cash', '30 Days', '60 Days', '90 Days', '120 Days']
},
bids: [{
type: Schema.ObjectId,
ref: 'Bid'
}],
looking: [{
type: Schema.ObjectId,
ref: 'User'
}],
sold: Boolean,
paid: Boolean,
delivered: Boolean,
sealed: Boolean,
initialPrice: Number,
value: Number,
cts: Number,
ppc: Number,
finalPrice: Number
});
BoxSchema.plugin(timestamps);
module.exports = mongoose.model('Box', BoxSchema);
And here is an example of documents that I try to fetch:
https://i.gyazo.com/38f2d16d6831b831adb3cc448ef74d01.png
Okay guys I managed to solve this problem. The problem was that the owner field in the box schema referenced a Supplier object, not a User object. So I solved it like so:
const { user } = res.locals;
return db.Supplier.findOne({ userId: user._id })
.populate('boxes').exec(function(err, supplier) {
if(err || !supplier) return res.sendStatus(404);
res.json(supplier.boxes);
});

How can I query an Array for a subdocument with mongoose?

I am looking to query a subdocument that contains an array.
You can think of this as an application similar to medium.com or tumblr.com:
I have a user schema, and User's have many Posts. My post schema has a 'tags' key which is an array I am trying to create a route which will display all posts that have a certain tag.
So for instance,
GET /user/posts/:tag
GET /user/posts/dogs
might return back the data for all posts (by any user) that have the tag 'dogs'
{
description: 'dogs are cool',
title: 'huskies',
tags: ['dogs','animals','outdoors'],
original_poster: '34255352426'
},{
description: 'My puppies are nice',
title: 'Puppies',
tags: ['pugs','dogs','small'],
original_poster: '44388342426'
},{
description: 'I like cats more than dogs',
title: 'Cats',
tags: ['kittens','cats','dogs'],
original_poster: '15708213454'
}
Here is my User Schema:
const mongoose = require('mongoose'),
Schema = mongoose.Schema,
PostSchema = require('./post-model.js');
let UserSchema = new Schema({
email: {
type: String,
required: true,
unique: true
},
username: {
type: String,
required: true,
unique: true
},
password: {
type: String,
required: false, //only required for local users
unique: false,
default: null
},
following: {
type: [Number],
required: false,
unique: false
},
followers: {
type: [Number],
required: false,
unique: false
},
posts: [PostSchema],
})
module.exports = mongoose.model('User',UserSchema);
Here is my Post Schema:
const mongoose = require('mongoose'),
Schema = mongoose.Schema;
let PostSchema = new Schema({
description: {
type: String,
required: false,
unique: false
},
title: {
type: String,
required: false,
unique: false
},
tags: {
type: [String],
required: true
},
original_poster: {
type: String,
required: true
}
});
module.exports = PostSchema;
EDIT:
to clarify my question, imagine that this was a regular js object, here is what a function to return all data relevant to a specific tag:
let users = [];
let user1 = {
username: 'bob',
posts: [
{
title: 'dogs r cool',
tags: ['cats','dogs']
},
{
title: 'twd is cool',
tags: ['amc','twd']
}]
};
let user2 = {
username: 'joe',
posts: [{
title: 'mongodb is a database system that can be used with node.js',
tags: ['programming','code']
},
{
title: 'twd is a nice show',
tags: ['zombies','horror-tv','amc']
},
{
title: 'huskies are my favorite dogs',
tags: ['huskies','dogs']
}]
}
users.push(user1);
users.push(user2);
function returnPostByTag(tag) {
let returnedPosts = [];
users.forEach((user,i) => {
user.posts.forEach((post) => {
if(post.tags.includes(tag)) {
let includespost = {}
includespost.title = post.title;
includespost.tags = post.tags;
includespost.original_poster = user.username;
returnedPosts.push(includespost);
}
})
})
return returnedPosts;
}
If you want to see a full repl where I use a plain js example here it is: https://repl.it/repls/LavenderHugeFireant
You can do the following using Mongoose to return all users where the tags array in any of the subdocuments in the posts array includes tag:
User.find({ 'posts.tags': tag }, function(err, users) {
if (err) {
// Handle error
}
let filteredPosts = users
.map(user => {
user.posts.forEach(post => post.original_poster = user.username)
return user
})
.map(user => user.posts)
.reduce((acc, cur) => acc.concat(cur), [])
.filter(post => post.tags.includes(tag))
// Do something with filteredPosts
// ...such as sending in your route response
})
...where User is your Mongoose model and tag contains the tag string you want to query (perhaps from your route request).
If you are using promises then you could do:
User.find({ 'posts.tags': tag })
.then(users => {
let filteredPosts = users
.map(user => {
user.posts.forEach(post => post.original_poster = user.username)
return user
})
.map(user => user.posts)
.reduce((acc, cur) => acc.concat(cur), [])
.filter(post => post.tags.includes(tag))
// Do something with filteredPosts
// ...such as sending in your route response
})
.catch(err => {
// Handle error
})

Resources