How to access a preexisting collection with mongoose?
当您使用Mongoose查询一个预先存在的集合时,您首先需要定义一个与该集合匹配的模型。这涉及到两个主要步骤:定义您的模式(Schema),然后根据该模式创建一个模型。以下是具体的步骤:定义模式(Schema):模式是一个对象,它定义了存储在MongoDB集合中的文档的结构和规则。这包括每个字段的类型、是否必填、默认值、验证等。const mongoose = require('mongoose');const { Schema } = mongoose;const myExistingCollectionSchema = new Schema({ // 在这里定义字段和它们的类型 name: String, age: Number, // 更多字段...});创建模型(Model):模型是一个与定义的模式相对应的构造函数,你可以使用这个构造函数与数据库中的集合进行交云。const MyModel = mongoose.model('MyExistingCollection', myExistingCollectionSchema);请注意,mongoose.model的第一个参数是你希望Mongoose连接到的集合名称。Mongoose默认会将模型名字转为小写并且复数形式来查找集合。如果您的集合名不符合这个转换规则,您需要在第三个参数中明确指定集合的名称:const MyModel = mongoose.model('MyExistingCollection', myExistingCollectionSchema, 'custom_collection_name');执行查询:一旦你有了一个模型,你就可以使用它来查询集合。Mongoose提供了多种方法来检索和操作数据,如 find, findOne, findById 等。// 查询所有文档MyModel.find({}, function(err, results) { if (err) throw err; // 处理查询结果 console.log(results);});// 根据条件查询单个文档MyModel.findOne({ age: { $gte: 18 } }, function(err, result) { if (err) throw err; // 处理查询结果 console.log(result);});// 根据ID查询单个文档MyModel.findById('某个文档的ID', function(err, result) { if (err) throw err; // 处理查询结果 console.log(result);});示例:假设我们有一个名为 users 的集合,其中包含姓名(name)、年龄(age)等信息。下面的示例代码展示了如何定义对应的模型并查询所有年龄大于等于18的用户。const mongoose = require('mongoose');const { Schema } = mongoose;// 连接到数据库mongoose.connect('mongodb://localhost/mydatabase', { useNewUrlParser: true, useUnifiedTopology: true });// 定义模式const userSchema = new Schema({ name: String, age: Number,});// 创建模型,假设集合名字正好是 `users` 的复数小写形式const User = mongoose.model('User', userSchema);// 执行查询User.find({ age: { $gte: 18 } }, (err, users) => { if (err) { console.error(err); } else { console.log('成年用户:', users); }});这样就可以查询到预先存在的 users 集合中所有年龄大于等于18的文档了。