When using Mongoose to query a pre-existing collection, you first need to define a model that matches the collection. This involves two main steps: defining your schema, and then creating a model based on that schema. Here are the specific steps:
- Defining the Schema: A schema is an object that defines the structure and rules for documents stored in a MongoDB collection. This includes the type of each field, whether it is required, default values, validation, etc.
javascriptconst mongoose = require('mongoose'); const { Schema } = mongoose; const myExistingCollectionSchema = new Schema({ // Define fields and their types here name: String, age: Number, // More fields... });
- Creating the Model: A model is a constructor corresponding to the defined schema, which you can use to interact with the collection in the database.
javascriptconst MyModel = mongoose.model('MyExistingCollection', myExistingCollectionSchema);
Note that the first parameter of mongoose.model is the name of the collection you want Mongoose to connect to. By default, Mongoose converts the model name to lowercase and plural form to locate the collection. If your collection name does not conform to this conversion rule, you need to explicitly specify the collection name in the third parameter:
javascriptconst MyModel = mongoose.model('MyExistingCollection', myExistingCollectionSchema, 'custom_collection_name');
- Executing Queries: Once you have a model, you can use it to query the collection. Mongoose provides various methods for retrieving and manipulating data, such as
find,findOne,findById, etc.
javascript// Query all documents MyModel.find({}, function(err, results) { if (err) throw err; // Process query results console.log(results); }); // Query a single document based on conditions MyModel.findOne({ age: { $gte: 18 } }, function(err, result) { if (err) throw err; // Process query results console.log(result); }); // Query a single document by ID MyModel.findById('some document ID', function(err, result) { if (err) throw err; // Process query results console.log(result); });
Example:
Suppose we have a collection named users containing information such as name (name), age (age), etc. The following example code demonstrates how to define the corresponding model and query all users with an age of 18 or older.
javascriptconst mongoose = require('mongoose'); const { Schema } = mongoose; // Connect to the database mongoose.connect('mongodb://localhost/mydatabase', { useNewUrlParser: true, useUnifiedTopology: true }); // Define the schema const userSchema = new Schema({ name: String, age: Number, }); // Create the model, assuming the collection name is the pluralized and lowercase version of 'users' const User = mongoose.model('User', userSchema); // Execute the query User.find({ age: { $gte: 18 } }, (err, users) => { if (err) { console.error(err); } else { console.log('Adult users:', users); } });
This will query all documents in the pre-existing users collection where the age is 18 or older.