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

Mongoose 如何查询预先存在的集合?

5 个月前提问
3 个月前修改
浏览次数28

6个答案

1
2
3
4
5
6

当您使用Mongoose查询一个预先存在的集合时,您首先需要定义一个与该集合匹配的模型。这涉及到两个主要步骤:定义您的模式(Schema),然后根据该模式创建一个模型。以下是具体的步骤:

  1. 定义模式(Schema):模式是一个对象,它定义了存储在MongoDB集合中的文档的结构和规则。这包括每个字段的类型、是否必填、默认值、验证等。

    javascript
    const mongoose = require('mongoose'); const { Schema } = mongoose; const myExistingCollectionSchema = new Schema({ // 在这里定义字段和它们的类型 name: String, age: Number, // 更多字段... });
  2. 创建模型(Model):模型是一个与定义的模式相对应的构造函数,你可以使用这个构造函数与数据库中的集合进行交云。

    javascript
    const MyModel = mongoose.model('MyExistingCollection', myExistingCollectionSchema);

    请注意,mongoose.model的第一个参数是你希望Mongoose连接到的集合名称。Mongoose默认会将模型名字转为小写并且复数形式来查找集合。如果您的集合名不符合这个转换规则,您需要在第三个参数中明确指定集合的名称:

    javascript
    const MyModel = mongoose.model('MyExistingCollection', myExistingCollectionSchema, 'custom_collection_name');
  3. 执行查询:一旦你有了一个模型,你就可以使用它来查询集合。Mongoose提供了多种方法来检索和操作数据,如 find, findOne, findById 等。

    javascript
    // 查询所有文档 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的用户。

javascript
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的文档了。

2024年6月29日 12:07 回复

Mongoose added the ability to specify the collection name under the schema, or as the third argument when declaring the model. Otherwise it will use the pluralized version given by the name you map to the model.

Try something like the following, either schema-mapped:

shell
new Schema({ url: String, text: String, id: Number}, { collection : 'question' }); // collection name

or model mapped:

shell
mongoose.model('Question', new Schema({ url: String, text: String, id: Number}), 'question'); // collection name
2024年6月29日 12:07 回复

Here's an abstraction of Will Nathan's answer if anyone just wants an easy copy-paste add-in function:

shell
function find (name, query, cb) { mongoose.connection.db.collection(name, function (err, collection) { collection.find(query).toArray(cb); }); }

simply do find(collection_name, query, callback); to be given the result.

for example, if I have a document { a : 1 } in a collection 'foo' and I want to list its properties, I do this:

shell
find('foo', {a : 1}, function (err, docs) { console.dir(docs); }); //output: [ { _id: 4e22118fb83406f66a159da5, a: 1 } ]
2024年6月29日 12:07 回复

You can do something like this, than you you'll access the native mongodb functions inside mongoose:

shell
var mongoose = require("mongoose"); mongoose.connect('mongodb://localhost/local'); var connection = mongoose.connection; connection.on('error', console.error.bind(console, 'connection error:')); connection.once('open', function () { connection.db.collection("YourCollectionName", function(err, collection){ collection.find({}).toArray(function(err, data){ console.log(data); // it will print your collection data }) }); });

Update 2022

If you get an MongoInvalidArgumentError: The callback form of this helper has been removed. error message, here's the new syntax using async/await:

shell
const mongoose = require("mongoose"); mongoose.connect('mongodb://localhost/productsDB'); const connection = mongoose.connection; connection.on('error', console.error.bind(console, 'connection error:')); connection.once('open', async function () { const collection = connection.db.collection("Products"); collection.find({}).toArray(function(err, data){ console.log(data); // it will print your collection data }); });
2024年6月29日 12:07 回复

I had the same problem and was able to run a schema-less query using an existing Mongoose connection with the code below. I've added a simple constraint 'a=b' to show where you would add such a constraint:

shell
var action = function (err, collection) { // Locate all the entries using find collection.find({'a':'b'}).toArray(function(err, results) { /* whatever you want to do with the results in node such as the following res.render('home', { 'title': 'MyTitle', 'data': results }); */ }); }; mongoose.connection.db.collection('question', action);
2024年6月29日 12:07 回复

Are you sure you've connected to the db? (I ask because I don't see a port specified)

try:

shell
mongoose.connection.on("open", function(){ console.log("mongodb is connected!!"); });

Also, you can do a "show collections" in mongo shell to see the collections within your db - maybe try adding a record via mongoose and see where it ends up?

From the look of your connection string, you should see the record in the "test" db.

Hope it helps!

2024年6月29日 12:07 回复

你的答案