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

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.

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 all keys + in a collection + mongodb +mongoose

I want to get all distinct keys from a collections in mongoDB.
I refereed the following links:
Get names of all keys in the collection
Querying for a list of all distinct fields in MongoDB collection and etc.
But still i didn't get the right solution...
As i am using mongoose in the first link reference syas runCommand is not a function.
As findOne() will give the first document keys alone but i need all distnct keys
userModel.findOne(condition, projection, callback)
Please share your ideas..
If you are using Mongoose 3.x, then you can try this :
userModel.find().distinct('_id', function(error, ids) {
// ids is an array of all ObjectIds
});
Or you can find all the documents and extract key from that like :
var keys = {};
var docKeys = [];
userModel.find({}, function(err, allDocs){
allDocs.forEach(function(doc){
docKeys = Object.keys(doc);
docKeys.forEach(function(docKey){
if(!keys[docKey]) keys[docKey] = true;
})
})
})
I have just written for getting logic, you can change according to your requirements and efficiency
Try like this you will get all of your keys defined into your mongoose model/Schema.
import Model from 'your_model_path'
for(let property in Model.schema.obj){
console.log("key=====>",property);
}

Remove an array value from mongodb collection document, sailsjs

I have an array like this on under user collection
How can i remove a single value from this array by using sails.js code
also i need to remove all post id from every users document if a post is deleted, is there any simplest and fastest way to remove from all documents too??
There are a couple of easy ways to do it if you're using the built-in ORM "Waterline", and they are basically equivalent.
The first is to run Model.update() and overwrite the array with the new value.
Model.update(id, { likes : [/* new array value */] }).then(...)
The other is to 1) find the object 2) pull the value off the array 3) save:
Model.findOne(id, function(err, document){
if(err) // handle err case
else {
document.likes = document.likes.filter(value => value !== 'stringToRemove')
document.save(function(err, saved){
... // do more stuff
})
}
})
Finally, unless you're using it for a very simple app, I cannot recommend using Waterline ORM with MongoDB. Save yourself a heap of headache and use Mongoose.

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 use a list of objects inside an object of MongoDB using Mongo-Skin?

I'm using mongoDB with mongoskin on top of Node.JS.
I have a list of images (collection 'images') and for each image I'd like to save a list of comments.
I believe the right way with mongodb is to use a list of comments inside of each Image document.
The problem - I have no idea how to do this. How do I use lists inside of documents? and how do I perform CRUD on them?
Many thanks for the help.
this is how you would do it with the driver (mongoskin is just a thin layer on top)
var id = new ObjectId();
var image = {_id: id, title:"some title".......}
collection.insert(image, {safe:true}, function(err, result) {
var comment = {title:'comment'}
collection.update({_id:id}, {$push:{comments:comment}}, {safe:true}, function(err, nrofUpdated) {
}
})
useful links
http://docs.mongodb.org/manual/
http://mongodb.github.com/node-mongodb-native/
There is no direct way to do the traditional CRUD on embedded objects. You can do Create and READ easily, but Update and Delete, and very rudimentary. You cannot select just a single embedded object; you can only select the parent object(the one that has _id). A list of embedded objects is an array with objects are entries.

Resources