You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Mongoose中不使用models、schemas直接读取MongoDB集合数据

MongoDB 无需定义 Model/Schema 直接操作集合的实现方案

现有代码无法正常运行的原因

你编写的代码中,find()方法执行后返回的是MongoDB游标对象,而非实际的查询结果数据集,直接打印无法得到预期的内容。

正确实现代码

只需要在find()后追加.toArray()方法,将游标转换为结果数组即可,修改后代码如下:

const res = await this.MongoBackupConnection.connection.db.collection(this.tableName).find().toArray()
console.info(res);

其他常用无模式操作示例

  • 带过滤条件查询
// 查询age字段大于18的所有数据
const filterRes = await this.MongoBackupConnection.connection.db.collection(this.tableName).find({ age: { $gt: 18 } }).toArray()
  • 插入单条数据
const insertRes = await this.MongoBackupConnection.connection.db.collection(this.tableName).insertOne({
  title: "测试内容",
  createTime: Date.now()
})
  • 批量更新数据
// 将所有status为0的文档修改为status为1
const updateRes = await this.MongoBackupConnection.connection.db.collection(this.tableName).updateMany(
  { status: 0 },
  { $set: { status: 1 } }
)
  • 删除指定条件数据
// 删除所有expireTime小于当前时间的文档
const deleteRes = await this.MongoBackupConnection.connection.db.collection(this.tableName).deleteMany({
  expireTime: { $lt: Date.now() }
})

内容的提问来源于stack exchange,提问作者Michał Topór

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.18 21:45:03