乐闻世界logo
搜索文章和话题

How to access a preexisting collection with mongoose?

1个答案

1

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:

  1. 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.
javascript
const mongoose = require('mongoose'); const { Schema } = mongoose; const myExistingCollectionSchema = new Schema({ // Define fields and their types here name: String, age: Number, // More fields... });
  1. 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.
javascript
const 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:

javascript
const MyModel = mongoose.model('MyExistingCollection', myExistingCollectionSchema, 'custom_collection_name');
  1. 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.

javascript
const 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.

2024年6月29日 12:07 回复

你的答案