将所有mongoDB数据打印到字符串nodejs

时间:2015-06-05 16:28:30

标签: javascript node.js mongodb

我有一个像这样的示例mongo文档:

> db.chat.find().pretty()
{
    "_id": ObjectId("555f1c0c7f4b820758b439b0"),
    "user": "Guest1",
    "friend": [{
        "userfriend": "Guest2",
        "noidung": [{
            "method": "send",
            "date": "2015-05-22T19:11:34+07:00",
            "content": "allloooo"
        }, {
            "method": "receive",
            "date": "2015-05-23T09:08:14+07:00",
            "content": "yes man"
        }]
    }, {
        "userfriend": "Guest3",
        "noidung": [{
            "method": "send",
            "date": "2015-05-23T15:42:34+07:00",
            "content": "foo 15:42"
        }, {
            "method": "receive",
            "date": "2015-05-23T15:42:45+07:00",
            "content": "bar 15:43"
        }]
    }]
}

在我的server.js中,我使用此代码打印所有数据:

var chathistory = db.collection('chat');
chathistory.find().toArray(function (err, docs) {
    console.log(docs)
});

我在终端上输入了这个日志:

[ { _id: 555f1c0c7f4b820758b439b0,
    user: 'Guest1',
    friend: [ [Object], [Object] ] } ]

'朋友'字段不打印全部,仅打印[Object],因此如何获取完整数据。

1 个答案:

答案 0 :(得分:3)

要打印所有数据,请使用 JSON.stringify() 方法

db.collection('chat').find().toArray(function(err, docs) {
    console.log(JSON.stringify(docs));
});