Don't know how to write complex Mongoose query - node.js

Here is the schema used to display current tournaments in one country:
var TournamentSchema = new mongoose.Schema({
name: String,
location: String,
googlelink: String,
description: String,
format: String,
date: Date
closedate:Date
type:String
});
The webpage also has filters like in ecommerce sites. If suppose I get one query from url like:
https://www.example.com/format=5v5%7v7&&location=hyd&&ahmedabad
I need to make query for tournaments which are 5v5 or 7v7 format and which are in Hyd and Ahmedabad.
I need to write generalised query as I don't know about number of places and format.
I don't know how to do this. Can someone help me out?

Here is an example of a query I wrote that uses mongoose $or.
Event.find( { $or: [{ joiners: req.user._id }, { creator: req.user._id}] } )
.populate('creator')
.exec(function(err, goevent){
if(err){
console.log(err)
} else {
res.json(goevent)
}
})
Basically in your query param {} you can pass in something like this:
{ $or: [ { query: one}, {query: two} ] }
Like so:
Model.find({ $or: [ { query: one}, {query: two} ] }, function(err, data){
//err & success handlers
}
Once you figure that out, you can use a bunch of other logical operators as well, like $and.
if the object you are querying is nested you just do 'some.property' (use string syntax when accessing objects with dot notation)

Related

Using Mongoose to query an array of objects

I've got a MongoDB database collection called Dealers structured a bit like this:
{
... dealer info goes here like address etc,
"user_logins": [
{
"Username": "something",
... other stuff
}
]
},{
... next dealer etc...
I'm using Mongoose to try and query on the user_logins.Username using this:
Mongoose model
const myTest = mongoose.Schema({
Username: {
type: "String",
required: true
}
}, { collection: "Dealers" })
module.exports = mongoose.model("Dealer", myTest);
The query
Dealer.find({'user_logins.Username' : 'something'}, (err, result) => {
if (err) {
console.log(err);
} else {
res.json(result);
}
});
All the Username's are distinct. But instead of returning the one matching document, it seems to be returning the whole Dealers collection.
I followed this example.
https://kb.objectrocket.com/mongo-db/use-mongoose-to-find-in-an-array-of-objects-1206
What am I doing wrong please?
Thanks.
EDIT: It seems fine if I try to find something on the root level. EG. Company name, address etc. But if I try to query an imbedded array of objects, that's when it pulls the whole collection. I don't get it.
Found the answer.
My model was wrong. It needed to reflect the actual structure of my data, which does kind of make sense.
This worked:
const myTest = mongoose.Schema({
user_logins: [{
Username: {
type: "String",
required: true
}
}]
}, { collection: "Dealers" })
module.exports = mongoose.model("Dealer", myTest);

$push into deeply nested array mongoose

my userSchema is as follows...
const userSchema = new mongoose.Schema({
firstName: { type: String },
lastName: { type: String },
movies: [
{
name: String,
duration: Number,
actors: [{ name: String, age: Number }]
}
],
});
In my NodeJS app with express I am trying to update my actors array to have another actor with value stroking from req.body.
I thought that I could do something like this...
await User.updateOne(
{
_id: req.user.id
movies._id: req.params.id
},
{
$push: { 'movies.actors': req.body }
}
)
I thought this would push an actor into the specified movie req.params.id but does nothing instead.
Try using positional operator $ in this way:
db.collection.update({
"_id": 1,
"movies._id": 1
},
{
"$push": {
"movies.$.actors": req.body
}
})
Note the only diference is the use of $. But with positional operator you are saying mongo where push the new data.
As docs says:
The positional $ operator identifies an element in an array to update without explicitly specifying the position of the element in the array.
So you can update the element movies.actors pushing new data without knowin the position of the element.
Example here
Try this:
await user.updateOne(
{$and:[{_id: req.user.id},{movie.name: 'I am Legend'}]},
{$set: { movies.actors:req.body}},
);

Mongoose update or insert many documents

I'm trying to use the latest version of mongoose to insert an array of objects, or update if a corresponding product id already exists. I can't for the life of me figure out the right method to use (bulkWrite, updateMany etc) and I can't can't seem to figure out the syntax without getting errors. For example, i'm trying
Product.update({}, products, { upsert : true, multi : true }, (err, docs) => console.log(docs))
this throws the error DeprecationWarning: collection.update is deprecated. Use updateOne, updateMany, or bulkWrite instead. MongoError: '$set' is empty. You must specify a field like so: {$set: {<field>: ...}
and using updateMany just gives me the $set error. I can't seem to find any examples of people using this method, just wondering if somebody can provide me with an example of how to properly use this.
To be clear, I generate an array of objects, then I want to insert them into my db, or update the entry if it already exists. The field I want to match on is called pid. Any tips or advice would be greatly appreciated!
EDIT:
My product schema
const productSchema = new mongoose.Schema({
title : String,
image : String,
price_was : Number,
price_current : {
dollars : String,
cents : String
},
price_save_percent : String,
price_save_dollars : String,
price_save_endtime : String,
retailer : String
})
const Product = mongoose.model('Product', productSchema)
an example of the products array being passed
[
{
title: 'SOME PRODUCT',
image: '',
price_was: '139.99',
price_current: { dollars: '123', cents: '.49' },
price_save_percent: '12%',
price_save_dollars: '16.50',
price_save_endtime: null,
pid: 'VB78237321',
url: ''
},
{ ... },
{ ... }
]
You basically need bulkWrite operation
The array you want to update with
const products = [
{
title: 'SOME PRODUCT',
image: '',
price_was: '139.99',
price_current: { dollars: '123', cents: '.49' },
price_save_percent: '12%',
price_save_dollars: '16.50',
price_save_endtime: null,
pid: 'VB78237321',
url: ''
}
]
The query for bulk update
Model.bulkWrite(
products.map((product) =>
({
updateOne: {
filter: { retailer : product.pid },
update: { $set: product },
upsert: true
}
})
)
)

Mongoose findOne returns empty array field

I have a simple embedded document:
{
"username":"user001",
"name":"John",
"tasks":[
{
"id":0,
"title":"Candy",
"description":"Lots of candy for you",
"category":"food",
"cost":2500,
"candyTypes":[
{"name":"gum", "type":"sweet", "price":"2"},
{"name":"chocolate", "type":"tasty", "price":"3"}
]
}
]
}
When I try to query the task data through the mongo shell, I get everything:
db.users.findOne({ 'username': 'user001', 'tasks.id':4 }, {'tasks.$':1})
/* returns */
"tasks":[
{
"id":0,
"title":"Candy",
"description":"Lots of candy for you",
"category":"food",
"cost":2500,
"candyTypes":[
{"name":"gum", "type":"sweet", "price":"2"},
{"name":"chocolate", "type":"tasty", "price":"3"}
]
}
]
But when I try to do the same in mongoose, the candyTypes array comes back empty:
Users.findOne({ 'username': username, 'tasks.id':taskId }, {'tasks.$':1}, function (err, data) {
console.log(data);
});
/* returns */
"tasks":[
{
"id":0,
"title":"Candy",
"description":"Lots of candy for you",
"category":"food",
"cost":2500,
"candyTypes":[]
}
]
I'm pretty new to MongoDB and Mongoose, but after searching and looking through documentation, I can't figure out what I'm missing.
UPDATE
I couple users requested it, so here is my mongoose schema:
var UserSchema = new mongoose.Schema({
username:String,
name:String,
tasks:[{
id: Number,
title: String,
description:String,
category: String,
cost: Number,
candyTypes:[{
title:String,
type:String,
value:String
}]
}]
});
With Mongoose, you have to populate candyTypes array:
Users.findOne({ 'username': username, 'tasks.id':taskId }, {'tasks.$':1})
.populate('candyTypes')
.exec(function (err, data) {
console.log(data);
});
See docs: http://mongoosejs.com/docs/populate.html
I think it's related to you declaring a field called type which also has a special meaning in Mongoose, namely to signify the type of a field.
If you rename that field to something else (candyType), it'll probably work better.
Alternatively, you can use the typeKey option to make Mongoose use a different property name to signify field type.
As an aside, your document contains a field price but your schema names it value.

Using mongoose, how do I filter and then group by?

I am using mongoose and so far the query I use gets me all of the critiques based on a docId. I would like to group this result by distinct editors now. Except, my editors is an object.
This is what my critique query looks like:
Critique.find({docId:req.params.docId}).populate('editor', 'name username').exec(function(err, critiques){
if(err){
console.error("Cannot find critiques with docId: " + critiques.docId);
}
console.log(critiques);
res.jsonp(critiques);
});
This is my model I am querying:
var CritiqueSchema = new Schema({
className : String,
content: String,
eleId: Number,
type: String,
comments: String,
isAccepted: Boolean,
classes: String,
docId:{
type: Schema.ObjectId,
ref: 'Composition'
},
created: {
type: Date,
default: Date.now
},
editor: {
type: Schema.ObjectId,
ref: 'User'
},
});
UPDATE new query:
Critique.aggregate(
[ {$match : {docId : mongoose.Types.ObjectId(req.params.docId)}},
{$group : { _id : "$editor", critiques: { $push: "$$ROOT" } } }
]).exec(function(error, result){
if(!error)console.log(result);
else console.log(error);
});
What you need is $group in the aggregation framework. But aggregation and population don't go along. So you have two options populate and group the results by yourself by writing a loop or you can use $group to group them and then query each editor manually. The second is better as there will no duplication in editor queries whereas in population there will be significant duplication going on.
Critique.aggregate(
[{
$match:
{
docId: ObjectId(req.params.docid)
}
},
{ $group : { _id : "$editor", critiques: { $push: "$$ROOT" } } }
],
function(err,result){
if(!err){
/* result will be of the form:
[{_id:<an editor's objectid>,critiques:[{<critique1 document>},{<critique2 document>}...]}...]
*/
//you will have to manually query for each distinct editor(result[i]._id) which sucks
//because the call will be asynchronous in the loop and you can't send your response without using async library
//another option would be to use the $in operator on an array of the distinct critiques:
var editors = result.map(function(x) { return x._id } );
User.find({_id:{$in:editors}},{'username':1},function(err,editorDocs){
var editor_ids=editorDocs.map(function(x){return x._id})
var index;
for(var i=0;i<result.length;i++){
index=editor_ids.indexOf(result[i]._id);
result[i].editor=editorDocs[index].username;
}
//result is your final result. In the editor field of each object you will have the username of the editor
})
}
})
Check the docs for $$ROOT.

Resources