37

Do i understand correctly, that if i want to query a collection, i have to do the following:

    var mongoose = require("mongoose");

mongoose.connect();

var db = mongoose.connection;

db.on('open', function callback () {

    var kittySchema = mongoose.Schema({
        name: String
    })

    var Kitten = mongoose.model('Kitten', kittySchema)


    Kitten.find(function (err, kittens) {
        console.log(kittens);
    })

});

Do i have to specify the schema each and every time, even when there is already a collection of kittens?

Why can't i do something like db.Kittens.find()?

1
  • 1
    db.Kittens.find() would be synchronous Jan 29, 2014 at 11:33

5 Answers 5

49

From the Mongoose home page:

Mongoose provides a straight-forward, schema-based solution to modeling your application data and includes built-in type casting, validation, query building, business logic hooks and more, out of the box.

Mongoose cannot infer from a collection of potentially unique documents a schema. MongoDB doesn't enforce schema upon the documents that are stored in a collection.

So, Mongoose adds a layer upon the NodeJS native driver (here) that many find more productive. It's not a requirement to use though with MongoDB when using Node.JS.

Mongoose needs two things fundamentally to work:

  1. Schema == this defines the document structure (reference). You can add validation, new methods, add virtual properties, use data types, establish references to other collections (models).
  2. Model == this is the class that is then used at run time to express queries against collections (reference). A Schema definition is used to build a Model.

So, as you saw in the sample you pasted, there is a kitten Schema defined, and then a Model Kitten is created. What's nice about using a schema and model is that Mongoose then enforces the properties/fields that are available.

You only define the Schemas and Models once in an application. So, usually as the application starts, you'll need to execute code to define them, and then use the Model instances as needed throughout the application life-cycle.

There are many more reasons you'd want to use Mongoose potentially.

You're absolutely right though, you could just use something more direct, without a schema by using the NodeJS native driver. The syntax would be similar to what you showed, but a bit more complex:

MongoClient.connect("mongodb://localhost:27017/exampleDb", function(err, db) {
  if(err) { return console.dir(err); }

  var collection = db.collection('kittens');

    collection.find().toArray(function(err, kittens) {
        // here ...
    });    
});

Rather than the simple:

Kitten.find(function(err, kittens) {

});

Plus, when using Mongoose, you may find that writing more complex queries is easier to write and read:

Kitten.find().where('name', 'Harold').exec(/*callback*/);

I'd suggest reading through more of the documentation to get a better feel for the framework and whether it's a good match for your needs. The documentation is a bit scattered about unfortunately, but if you go through the sub headings of the Guide heading, you'll have a lot of good information available.

44

try this..

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const ProductSchema = new Schema({}, { strict: false });
const Product = mongoose.model('Product', ProductSchema, 'products');

module.exports = { Product };
1
  • 9
    This answer violates "without passing schema" part of the question. But it really works. It helped me to access old data related to an updated Schema, just to update them to the new format. Thanks.
    – ruwan800
    Oct 8, 2019 at 12:36
22

You cannot use Mongoose without schemas. If you want to use MongoDB without schemas, don't use Mongoose, use something like mongodb instead.

1
  • 2
    Thank you so far. I guess my problem is that i find mongoose's docs very confusing. Would you mind to briefly explain the terms of schemas and models and how they work together? Jan 29, 2014 at 11:50
0

IMO, If you don't need schemas you can use mongodb-nodejs driver!

But in some cases:

  1. You don't want to maintain schemas in a repo but still use mongoose added features (or)
  2. You don't want to use existing schema/create new one in a piece of code/place in a large repo.

So, you no need to create schemas to query/write mongoDB while using mongoose, below code uses mongoose to create a connection but no schema is needed to query the DB!

Note: Works only with mongoose versions < 6:

mongoose.connection.db.collection('collectionName', (err, collection) => {
    collection.find({}, {}, (err, document) => { /** .... */ })
})

mongoose version 6 was released at the end of 2021 & is better to use it, as latest versions will have more features to offer (You'll definitely need v6 if your mongoDB server is > 5.0 but not needed if mongoDB server version is < 5.0. REF.:mongoose-mongoDB-version-compatibility).

Note: Reason why above code doesn't work with mongoose versions > 6: mongoose internally uses mongoDB-nodejs driver to talk to mongoDB server. mongoose versions > 6 brings mongoDB-nodejs driver version > 4 in which above code is no longer supported but an alternative exists. REF. : Issue-Report/Ticket

Keywords used:

mongoDB server: Actual Mongo Database server.

mongodb-nodejs driver: mongodb nodejs driver that can be used to talk to mongoDB server from Node.Js.

mongoose: Mongoose is an Object Data Modeling(ODM) library for accessing mongoDB via nodejs (Making no-SQL mongoDB, schema based)

-1
// With model
const model = await conn.model(modelName, schema, collectionName)
const documents = (await model.find({})).map(doc => doc._doc)

// Without model
const documents = await conn.db.collection('Apple').find().toArray()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.