How to use find where query in Mongoose - mongodb

I've been writing a lot of MySQL lately so I've forgotten how to write some Mongoose queries. I am trying to search my database to find stocks where the user is the same as the req.params.user. below is the route and my Schema so you can see what's going on. I'm running it in Post man, but it's giving me a "Cannot GET /stock/user-stocks/Sina" Error. I also left a sample stock in my DB for reference
router.get('user-stocks/:user', (req, res) => {
Stock.find({ user: toString(req.params.user)})
.then((stocks) => res.json(stocks))
.catch(err => res.json(err))
})
const stockSchema = new Schema({
user: {type: String, required: true},
symbol: {type: String, required: true},
target: {type: Number, required: false},
stop: {type: Number, required: false},
description: {type: String, required: false},
date: {type: Date, required: false}
})
{
"_id": "5ff284d07b93cd434cae9a08",
"user": "Sina",
"symbol": "AAPL",
"target": 200,
"stop": 100,
"description": "Get money",
"date": "2021-01-03T00:00:00.000Z",
"__v": 0
},

Related

mongoose query where id not in other model

so I have this kind of model
const vetSchema = new mongoose.Schema({
username: {type: String, required: true, trim: true, unique: true},
email: {type: String, unique: true, trim: true,},
expYear: {type: Number},
KTP: {type: String, unique: true, trim: true},
cert_id: {type: String, unique: true, trim: true, select: false},
})
const clinicSchema = new mongoose.Schema({
vet: [{type: mongoose.Schema.Types.ObjectID, ref: 'vet'}],
)}
what I want to do is finding vet by username, which the vet ID is not included in the clinic based on clinic ID, the query to find the vet is {username: {$regex: (?i)${keyword}.*}}
for example, we have this data
Clinic = [{
"_id" : ObjectId("5e57a45836d300b188f4444a"),
"vet": [ObjectId("5e0742fc9d4b20100f89b626"),ObjectId("5e53698fd2b9ee43e7693e01")]
}]
Vet = [
{
"_id" : ObjectId("5e0742fc9d4b20100f89b626"),
"username": "VetClinic"
},
{
"_id" : ObjectId("5e55df62576bc9811877033e"),
"username": "VetNotClinic"
},
{
"_id" : ObjectId("5e53698fd2b9ee43e7693e01"),
"username": "VetClinic"
},
]
what i want is if I find Vet it only shows VetNotClinic because VetClinic is included in the clinic's ID, any good query / agregate?
you can use $nin to query where a field is "not in" an array like so
Vet.find({
username: {$regex: (?i)${keyword}.*},
_id: {$nin: clinic.vet}
})

MongoDB - Getting records made by user

I'm working with Mongodb, and was wondering on how to get records made by the user. In the below example I have to records each with different emails (createdBy), but how do I get the records by the current user logged in?
Schema result:
var resultSchema = new Schema({
test: { type: String, required: true, lowercase: true},
status: { type: String, required: true, lowercase: true},
date: { type: Date, required: true},
amount: { type: Number, required: true},
createdBy: { type: String, required: true},
});
Schema user:
var userSchema = new Schema({
email: { type: String, required: true, lowercase: true},
username: { type: String, required: true, lowercase: true},
password: { type: String, required: true}
});
Database:
"recipe": [
{
"_id": "5b7af572a1051b1b18aec627",
"test": "asassdasdasd",
"status": "waiting",
"date": "2018-08-06T22:00:00.000Z",
"amount": 2,
"createdBy": "test#outlook.com",
"__v": 0
}
]
"recipe": [
{
"_id": "5b7af572a1051b1b18aec621",
"test": "test2",
"status": "waiting",
"date": "2018-08-06T22:00:00.000Z",
"amount": 2,
"createdBy": "notTest#outlook.com",
"__v": 0
}
]
I tried this, but this returns empty:
router.get('/userResults', (req, res) => {
Result.find({createdBy: req.body.createdBy}, (err, result) => {
})
})
To say the user is logged in or not and to identify the user who is logged in, I am sure you have some mechanism to get the Email ID of the current user.
So ideally you should have access to the Email ID of the user who is logged in and making the API call.
Provision a middleware to parse the email id from every request instead of making a Database call to check the user's email ID.
Query : db.resultSchema.find({createdBy: parsed_email_id_from_api_request}
One way to do it using JWT is parse the token using a middleware and forwarding the email or any other relevant field to the request where you make the Database call to check the "results" collection.

MongoDB not saving User

Trying to do a simple CRUD for a user.
I am passing name, email, password, location, avatar through a sign up form from React/Redux.
I am getting an error during the save which says the following about a duplicate key error --
(node:30190) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): WriteError({"code":11000,"index":0,"errmsg":"E11000 duplicate key error index: heroku_10vr0vgl.users.$googleId_1 dup key: { : null }","op":{"avatar":"avatar.jpg","slug":"jane","id":"cj7nl39w50000amcaool50zcp","name":"Jane","email":"admin#jane.com","password":"$2a$10$envMKYq6xFCkZGpYVd4rEel4g5TGijFOEnr.ayMymHM1ph0/1luGC","location":"Los Angeles","_id":"59bd5e9478537875ee6b8939","createdAt":"2017-09-16T17:25:40.863Z","campaigns":[],"role":"NORMAL","__v":0}})
Looks to be something about a duplicate val, but googleID for ex is not required.
I only have a mock user in the user collection that looks like the following --
[
{
"_id": {
"$oid": "59a070dea4de3af502af7d5c"
},
"avatar": "avatar.jpg",
"name": "John Doe",
"role": "ADMIN",
"slug": "john-doe",
"id": "1",
"email": "admin#johndoe.com",
"location": "Los Angeles",
"campaigns": ["1"],
"twitterId": "refinery29",
"password": "test1234"
}
]
The user model looks like the following --
import mongoose from 'mongoose';
const Schema = mongoose.Schema;
const userSchema = new Schema({
name: {type: 'String', required: true},
role: {type: 'String', default: 'NORMAL', required: true},
location: {type: 'String'},
slug: {type: 'String', required: true, index: {unique: true, dropDups: true}},
campaigns: {type: ['String'], default: []},
avatar: {type: 'String', required: true},
email: {type: 'String', index: {unique: true, dropDups: true}},
id: {type: 'String', required: true, index: {unique: true, dropDups: true}},
googleId: {type: 'String'},
facebookId: {type: 'String'},
twitterId: {type: 'String'},
createdAt: {type: 'Date', default: Date.now, required: true},
password: {type: 'String'},
});
export default mongoose.model('User', userSchema);
Looks like I had an existing index reference. I dropped my user collection and saved. All is well!

How findOne in mongoose

How find comment inside commentUnders?
comments: [{
nickName: {type: String, required: true},
comment: {type: String, required: true},
commentUnders: [{
nickName: {type: String, required: true},
comment: {type: String, required: true},
}]
}]
I tried this but it did not work.
Post.findOne({'comments._id' : req.body._idComment},
{'comments._id': $elemMatch: req.body._idComment,
'commentUnders._id': $elemMatch: req.body._idCommentUnders}, function(err, data) {
console.log(data);
});

Modeling with MongoDB and Mongoose

I have a simple app which lists tour guides and reviews left by users about each guide. Any user can give be a guide and can give reviews. My scheme for a user is:
var User = new mongoose.Schema({
firstName: { type: String, required: true, unique: true },
lastName: { type: String, required: true, unique: true },
email: { type: String, required: true, unique: true },
password: { type: String, required: true}
isGuide: Boolean,
rating: {type: Number, "default": 0, min: 0, max: 5},
reviews: [reviewSchema]
});
var Review = new mongoose.Schema({
userId: {type: Schema.ObjectId, ref: 'User'},
author: {type: String, required: true},//contatenation of firstName and lastName of user that wrote review
rating: {type: Number, required: true, min: 0, max: 5},
reviewText: {type: String, required: true},
createdOn: {type: Date, "default": Date.now}
});
mongoose.model('User', User);
I want to be able to:
1/ show a guide and all that guide's reviews
2/ show all a user's reviews
3/ show all guides a user has reviewed
I think my schema above is fine for 1. But is it suitable for 2 and 3? Am I understanding the MonboDB philosophy correctly?