Search a value in all collections of MongoDB database using Mongoose? - mongodb

I am new to Mongoose. I am struck to get data in every collection in Database.
I have some collections with a field country.
Lets say company_Information is collection having country as a field.
var companyInformation = new Schema({
....
country:{type: String},
..
})
mongoose.model('company_Information',companyInformation);
similarly country field may present in some other collection.
Instead of searching a value of country in each collection using
company_Information.find({ 'country': 'India' })
someCollection.find({ 'country': 'India' })
someCollection2.find({ 'country': 'India' })
is there any way to search a record in every collection in database?
Working example would help me.
Thank you.

For example you can use something like this:
const mongoose = require('mongoose');
const findAllCountries = (country_name)=>{
let models = [];
models.push(mongoose.models.someCollection1);
...
models.push(mongoose.models.someCollectionN);
return Promise.all(models.map(model=>model.find({'country': country_name})));
}
So you can use this function like this:
findAllCountries('USA').then(result=>{
console.log(result);
}).catch(err=>{throw err;})

Related

Format response from mongoose into a model

How do you go about formatting the data response from mongoose? For a simple Post Schema
const postSchema = new mongoose.Schema({
title: {
type: String,
required: true,
}
},{
timestamps: true
});
Whenever I do a GET request to find all the post, It returns me all its fields including _id and __v in which I wouldn't want to return those fields in an API.
Is there a way I would select only certain fields that I would want to return?
As far as I've found was that I could set a second parameter of title onto my query and it would return only the _id and title.
const post = await Post.find({},'title');
I find the method above isn't the proper way to filter fields in cases in the future where the values are deeply nested object and we would like to pick out certain values.
Is there perhaps a way to create a Model/Class and pick the fields based on the Model/Class and return the respond?
You can use select from mongoose.
You can either select only the fields you want.
var find = await model.find({}).select("my_field")
Or not show the fields you don't want
var find = await model.find({}).select("-my_field")
Check the documentation

How can I dynamically build a mongoose query that has an objectId?

I'm trying to dynamically build a mongoose query. The problem I'm having is that I can't figure out how to do this when the query contains an objectId.
I'm using mongoose 5.4.6.
My mongoose schema looks something like this:
stuff: String,
user: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
},
moreStuff: String,
});
I need to dynamically build my query, and one of the possible fields to query for is user. The fields to query for are sent to the server via a params object. When the field I'm querying for is stuff, then it's easy. I just do something like the following:
let query = {};
query.stuff = params.stuff;
this.model('MyModel').find(query)...
However, I can't figure out how to search for user, because params.user is just the string version of the mongo id, but it needs to be formatted as objectId("params.user") for the query to work. That is, I need something like:
query.user = objectId("params.stuff");
How can I get this to work?
I usually do like this.
const ObjectId = require('mongodb').ObjectID
const MyModel = require('../models/mymodel')
let query = MyModel.findOne()
query.where('_id').equals(new ObjectId(params.stuff))

Data Saves to MongoDB Database but not views in command

I use this code to store my data into MongoDB database but it does not view in the database .. and when I use find() to find, it shows my data but not shows when I use db.pick.find() in command. I may be missing something when I setup mongo so please help me.
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/pick', { useNewUrlParser: true })
mongoose.connection.once('connected', function(){
console.log("Open Connection")
})
var catSchema = new mongoose.Schema({
name: String,
age: Number
});
var Cat = mongoose.model("Cat", catSchema);
var newc = new Cat({
name: "cutie",
age: "4"
});
newc.save((err,c) =>{
if(err){
console.log("NewC Err")
}else{
console.log(c)
}
});
Okay atul,
Your database's name is Pick, but when you do this query:
db.pick.findOne({}), you're technically saying that the database must find a document from the pick collection. But looking at the code, cat is the name of your collection.
you can use the show collections; command to get the collection names in mongodb and then you can query like this:
Select the Database
use pick;
get the collection list
show collections;
query the collection
db.collectionName.findOne({})

mondgo db does not save with large documents

I'm iterating over a an object with 10000 key/val pairs and creating 'gameItem' docs and adding them to my 'items' field as a hash object and then saving them to my mongo collection like so.
Here's my main collection
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var myItemDbSchema = new Schema({
db_num: Number,
last_updated: Number,
items: {type: {}, default: {}}
}, { minimize: false });
module.exports = mongoose.model('myItemDb', myItemDbSchema);
and then my logic
PartnerAPI.getItems(function(err, partnerItems){
myItemDb.findOne({"db_num": 1}, function(myItemDB){
for(var partnerItem in partnerItems){
if(!myItemDB.items[partnerItem]){
var newItem = new gameItem({
name: partnerItems[partnerItem].name
});
myItemDB.items[partnerItem] = newItem;
}
myItemDB.markModified('items');
myItemDB.save(function(err){
logger.info("Saved");
});
}
});
});
partner items looks like this
{
'ballistic-weapon-1':{name:'bl1', value:'rare'}
},
{
'ballistic-weapon-2':{name:'bl2', value:'rare'}
}
This works fine if I only add no more than 300 to the items field and then mark items as modified and then save... but if I try to add all 10,000 and try to save - they don't. Is there a size limit for how many docs I can add to a field with a type {}?
Is there a better way to save these docs without having to write some logic to limit how many saves I do each iteration?
There is 16mb document limit. So if your document (BSON) is larger than 16 mb, mongodb throws exception.
docs: https://docs.mongodb.com/manual/reference/limits/

How to update a object in mongodb via mongoose?

I have mongoose schema as:
var Organization = new Schema({
name: String,
address: {
street : String,
city: String
}
}, { collection: 'organization' });
How do I update only street part of address for an organization via mongoose?
I can't find any docs that cover this simple case so I can see why you're having trouble. But it's as simple as using a $set with a key that uses dot notation to reference the embedded field:
OrganizationModel.update(
{name: 'Koka'},
{$set: {'address.street': 'new street name'}},
callback);
Now you can update directly .
OrganizationModel.update(
{name: 'Koka'},
{'address.street': 'new street name'},
callback);
Using Document set also, specified properties can be updated. With this approach, we can use "save" which validates the data also.
doc.set({
path : value
, path2 : {
path : value
}
}
Example: Update Product schema using Document set and save.
// Update the product
let productToUpdate = await Product.findById(req.params.id);
if (!productToUpdate) {
throw new NotFoundError();
}
productToUpdate.set({title:"New Title"});
await productToUpdate.save();
Note - This can be used to update the multiple and nested properties also.