node.js - 我无法使用 result.ops 方法查看使用 insertMany 插入的所有文档

标签 node.js mongodb

我正在尝试在我的任务集合中插入新文档,并使用 result.ops 方法打印所有插入的文档

const mongodb = require('mongodb')
const MongoClient = mongodb.MongoClient

const connectionURL = 'mongodb://127.0.0.1:27017'
const databaseName = 'task-manager'

MongoClient.connect(connectionURL, { useNewUrlParser: true }, (error, client) => {
if (error) {
    return console.log('Unable to connect to database!')
}

const db = client.db(databaseName)

db.collection('tasks').insertMany([
    {
        description: 'Clean the house',
        completed: true
    },{
        description: 'Renew inspection',
        completed: false
    },{
        description: 'Pot plants',
        completed: false
    }
], (error, result) => {
    if (error) {
        return console.log('Unable to insert tasks!')
    }
    console.log(result.ops)  //returns undefined
    console.log(result)   // returns only 2 methods 
})
})   

//console.log仅返回2个方法insertedcounts和insertedids

最佳答案

https://stackoverflow.com/a/68424173/16483030 这是你的答案。在版本 4 中,insertOne 返回的 insertOneResult 只有 2 个属性:acked 和insertedId。 所以你可以使用insertedId。这是有道理的,因为如果是一个,则不需要数组。

关于node.js - 我无法使用 result.ops 方法查看使用 insertMany 插入的所有文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68378249/

相关文章:

php - 如何将laravel迁移文件迁移到mongodb

mongodb - 我可以在 MongoDB 中存储关系数据库结构吗

node.js - 如何从磁力链接或 infohash 创建 torrent 文件

mysql - 使用 mongoid(通过 ActiveRecord)作为延迟作业的后端有什么好处?

node.js - 集成多部分中间件来表达应用程序

node.js - 使用 package.json 一起运行 Node 服务器和 webpack

node.js - NodeJS/MongoDB - 字段仅添加一次?

node.js - 无法在重置密码中保存 Bcrypt 密码

node.js - 将上传的文件存储到 Express Js 的文件系统中

node.js - Mongoose:如何生成有效的 mongoose.Types.ObjectId?