How can I combine Schema and noSchema with Mongoose? - node.js

I know I have to define Schema's in Mongoose, but I have a case where I'm connecting to a MongoDB via
dsn = "mongodb://#{config.database.username}:#{config.database.password}##{config.database.host}/{config.database.name}"
mongoose.connect(dsn, (err) -> throw err if err)
And most of my writes will be using Models the way I'm supposed to. But there is this one read that I have to do from a Collection and it's Schema-less. Meaning, it's unprocessed data that was stored by another process. How can I successfully read from that then write to other collections using my Schemas?
If I use mongoose, can I not do this?

To start with you can just make a blank schema for it.
var OtherSchema = new Schema({}, {collection: 'your-collection-name'});
Mongoose.model('Other', OtherSchema);
// ..

Related

Mongoose find data from dynamic Collection

I am new to MongoDB & working on a MEAN application.
In the mongo database(I am using mongoose), the collections are adding dynamically from third party API like schoolList1,schoolList2,schoolList3,schoolList4,....
I am facing problem to find a solution to get data from collections, Like If a user sends the argument from FrontEnd to find data from schoolList3.
The find function should apply on that collection only & return the data.
I am unable to solve it that how should I get data without passing schema and did not get any other way.
Set collection name option for your schema from user's input:
var collectionName = 'schoolList3'; // set value from the input
var dataSchema = new Schema({/** your schema here **/}, { collection: collectionName });

How to get the defined indexes from Mongoose

I have been trying to find out the indexes which are already created via MongoDB manually( I have created 2d sphere indexes for two fields via mongobooster and creating one via schema by defining it). Now if i run this query in mongodbooster
db.collectionname.getIndexes();
It results me the 3 documents with name.key and which indexes i have used. I want to perform this same operation in mongoose i can't find a equivalent query for the same. I tried this
const indexes = OrderSchema.indexes();
console.log('index:', indexes);
But it gives me only one index which i have defined in schema that is _id i need two other fields as well which contains 2d-sphere index how can i get that too. What am trying to achieve here is if 2d sphere indexes are already created don't create an index else create an index that's all am trying to achieve here. Any help is appreciated Thanks
Yeah, you can't do it with a schema. You will need to create the model first, and then you can do something like this:
Order.collection.getIndexes({full: true}).then(indexes => {
console.log("indexes:", indexes);
// ...
}).catch(console.error);
If you dont have access to mongoose model, but the mongoose connection was created and you need to get the indexes from a collection you can access by this way:
const mongoose = require('mongoose');
mongoose.connect('myConnectionString', { useNewUrlParser: true }).then(() => {
getIndexes();
});
const getIndexes = async () => {
const indexes = await mongoose.connection.db.collection('myCollection').
indexes.forEach(function (index) {
console.log(JSON.stringify(index));
});
};

Mongoose validate Schema with no Model

I want to validate some inner elements of an object against schemas that are members of a larger schema before posting that object on the model correspondent to that larger schema.
Someone already asked this question and this answer has something similar on the second option proposed:
var p = new People({
name: 'you',
age: 3
});
p.validate(function(err) {
if (err)
console.log(err);
else
console.log('pass validate');
});
The problem is that before doing the validation one has to create a new model with var People = mongoose.model('People', peopleSchema);.
Does this mean in this case that a new collection 'People' will be stored in the MongoDB database?
Is the act of calling mongoose.model('People', peopleSchema); altering the database in any way?
If so, is there a way to do this validation without creating a new collection, in this case 'People'?
The schema I want to validate will be stored as a component of another document already in the database and I don't want to pollute the database with unused collections.

findOne not returning correct result( Mongo DB and nodejs)

I have stored a document in collection and when i am trying to retrieve it via findOne, it is returning me wrong result:
My Mongoose model is like:
var db = require('../db');
var mongoose = db.mongoose_var;
var companySchema = mongoose.Schema({
companyName:String
});
module.exports = mongoose.model('Company',companySchema);
Which then i am using in my server.js as :
var CompanySchema = require('./schemas/companySchema');
and when I am trying to find already inserted record as following:
CompanySchema.findOne({'Company.companyName':jsonObj.companyName},function(err,companyName){
console.log('companyName foudn:'+companyName);
if(companyName !== null){
res.status(404).json({status:'Name already in the DB'});
return;
}else{...
Its unable to find this record, but its returning probably the first record.
Folloing record is present in thedb:
When I am trying to add another company and using this findOne to check if this name already exists, findOne returns this record only. My log snippets
whereas mongo shell returns proper result only.
In mongo shell, I am using " " around field and values, not in findOne Api.
Thanks in Advance
You should probably use the following :
CompanySchema.findOne({'companyName':jsonObj.companyName},function(err,companyDocument){
if(err) console.log(err);
console.log('company found:' + companyDocument);
if(companyDocument){
res.status(404).json({status:'Name already in the DB'});
return;
}else{...
The mistake in your code was that you were using Company.companyName instead of companyName. companyName is the name of the field in the Company collection.
Hope this helps you.

How to check if collection exists in MongoDB with Node.js? [duplicate]

This question already has answers here:
Node.js - Mongoose - Check if a collection exists
(4 answers)
Closed 7 years ago.
Basically, I want to hide a div based on whether a collection exists or not. Does anyone know the simplest way to do so? I am using Mongoose and Express.js with Jade.
If you want to hit mongodb directly via the node.js native api you can use db.collectionNames():
List existing collections
List names
Collections can be listed with collectionNames
db.collectionNames(callback);
callback gets two parameters - an error object (if error occured) and
an array of collection names as strings.
Collection names also include database name, so a collection named
posts in a database blog will be listed as blog.posts.
Additionally there’s system collections which should not be altered
without knowing exactly what you are doing, these sollections can be
identified with system prefix. For example posts.system.indexes.
Example:
var MongoClient = require('mongodb').MongoClient , format = require('util').format;
MongoClient.connect('mongodb://127.0.0.1:27017/test', function(err, db) {
if(err) throw err;
db.collectionNames(function(err, collections){
console.log(collections);
});
});
http://mongodb.github.io/node-mongodb-native/markdown-docs/collections.html
You could use
db.system.namespaces.find( { name: dbName +'.' + collectionName } );
It contains entries for collections and indices, for existing collection it should return something like this:
{ "name" : "temp333.categories" }
To do it from mongoose you could define system.namespaces model and query.

Resources