Javascript 对象打印为对象对象

标签 javascript node.js

我对 Node 和 mongo 数据库都很陌生。我正在创建从 Node 到 Mongo 的连接并尝试 CRUD 操作。我的操作在 operations.js 中定义,我正在调用索引中的函数。

我面临的问题是当我从中打印回调参数时

coll.find({}).toarray() - 这就是我得到所需输出的结果

[
  {
    _id: 5ea4843b0f28320524d23f14,
    name: 'Vadonut',
    description: 'Test Vadonut'
  },
]

但是当我打印 index.js 的结果时,这是 operation.js 中函数回调的结果,我得到的输出为

[object Object]

我能得到这方面的帮助吗?????

index.js :

const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');
const dboper = require('./operations')
const url = "mongodb://localhost:27017/";
const dbname = "dishes";

MongoClient.connect(url,(err,client)=>{
    assert.equal(err,null);

    console.log("Connected correctly correct to the server");

    const db =client.db(dbname);


    dboper.insertdocument(db,{"name":"Vadonut","description":"Test Vadonut"},'dishes',(result)=>{
        console.log('Insert Document:\n'+result);

        dboper.finddocument(db,'dishes',(result)=>{
           console.log("Found Documents :\n"+result);
    })

})  

****operations.js****

const assert = require('assert');

exports.insertdocument = (db,document,collection,callback)=>{
    const coll = db.collection(collection);
    coll.insertOne(document,(err,result)=>{
        assert.equal(err,null);
        console.log("Inserted " + result.result.n + "documents inserted into the collection"+collection);
        console.log(result.ops);
        callback(result);

    })

};

exports.finddocument = (db,collection,callback)=>{
    const coll = db.collection(collection);
    coll.find({}).toArray((err,docs)=>{
        assert.equal(err,null);
        console.log(docs);
        callback(docs);
    })
};

最佳答案

[object Object]是对象的默认/自动字符串转换。

因此,如果您在字符串操作表达式中的任何位置使用对象,例如:

let x = {greeting: "hello"};
let str = "I would like to say the greeting " + x;
console.log(str);

然后,JS解释器会尝试转换你的对象x到一个字符串,默认的字符串转换将是 [object Object]所以你会得到以下结果:

 I would like to say the greeting [object Object]

您需要做的是要么避免在字符串表达式中的任何位置使用 Javascript 对象,要么使用 JSON.stringify() 显式地将对象转换为 JSON。在将其包含在字符串表达式中之前。

我会替换这个:

console.log("Inserted " + result.result.n + "documents inserted into the collection"+collection);

用这个:

console.log("Inserted ",  result.result.n, "documents inserted into the collection", collection);

然后,您将整个对象传递给 console.log()它将在它们上显示正常的对象,而不是让 JS 尝试将它们自动转换为字符串。

您还可以使用 JSON.stringify(result.result.n) 将这些对象手动转换为字符串形式然后在字符串表达式中使用它们。

关于Javascript 对象打印为对象对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61431910/

相关文章:

javascript - 为什么这个函数返回0

node.js - 使用 Node.js 和 mongoose 进行 MapReduce

node.js - 将 Johnny-Five 与 React 结合使用

javascript - 使用 Webhook 在 Slack 上发布自定义 JSON 消息

javascript - Jquery 鼠标悬停淡入/淡出(最佳实践)

JavaScript - 从 2 个下拉菜单中计算它们之间的值

javascript - hAxis 标签位置 Google Charts

javascript - SequelizeJS 映射在第 1000 个循环处停止

javascript - Node.js 回调不执行

javascript - 类型错误 : listener must be a function