【问题标题】:mongoose document to JSON猫鼬文档到 JSON
【发布时间】:2014-05-29 00:05:28
【问题描述】:

我正在尝试将一组 mongoose 文档作为普通的旧 JavaScript 对象返回。我有一个处理数据库查询的user.js 模块-

module.exports = function() {
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function callback() {
    console.log('connection successful');
});
var outingSchema = mongoose.Schema({
    id : String,
    location : String,
    date : Date,
    participantCount : Number,
    confirmedParticipantCount : Number,
    group : String
});
var Outing = mongoose.model('Outing', outingSchema);

this.dashboard = function() {
    var result = Outing.find({}, function(err, outings) {
        console.log('##################');
    });
    db.close();
    return result;
}
}

这是我的主要server.js 文件-

io.of('/user').on('connection', function(socket) {
console.log('Incoming connection to ' + socket.namespace.name);
var User = require('./real/user.js');
var UserObject = new User();
socket.on('dashboard', function(data) {
    socket.send(JSON.stringify(UserObject.dashboard(), null, 3));
})
});

就目前而言,这总是会导致异常 -

TypeError: Converting circular structure to JSON

我假设发生这种情况是因为猫鼬 Document 对象具有某种圆形结构。我怎样才能让dashboard() 方法只返回可以使用JSON.stringify() 转换为 JSON 的常规 JavaScript 对象?

我已经尝试在每个文档上循环 outings' and calling thetoObject()` 方法,但这也只会返回猫鼬 Document 对象。

同样奇怪的是,据我所知,语句 console.log('##################'); 从未执行过(我在控制台中看不到输出)。这是因为它在回调函数中吗?其他回调函数中的其他console.log() 语句工作正常。

【问题讨论】:

    标签: javascript json node.js mongodb mongoose


    【解决方案1】:

    您需要将“仪表板”函数作为回调。

    this.dashboard = function(callback) {
        Outing.find({}, callback);
    };
    

    您很少希望在使用 node.js 的请求之间实际关闭数据库。

    socket.on('dashboard', function(data) {
        UserObject.dashboard(function(err, results){
          if(err){
            //send the error to the socket
          }
          socket.send(JSON.stringify(results);
        });
    });
    

    【讨论】:

    • 这似乎可以解决问题。不过,我真的不明白我做错了什么。为什么dashboard 必须是回调?此外,JSON 字符串包括 _id__v 属性。有什么办法可以从代表中排除这些吗?
    • 你可以忘记后续问题的第二部分。我使用query.select('- excludedField') 进行投影。您能解释一下为什么我必须将dashboard 转换为回调吗?
    • 因为nodejs是非阻塞的,你不会马上得到查询的结果。它们不像某些语言那样从语句中返回。当结果准备好时执行回调函数。阅读 nodejs 和回调。 theprojectspot.com/tutorial-post/nodejs-for-beginners-callbacks/…
    • 知道了!非常感谢您的帮助:)
    猜你喜欢
    • 2017-05-07
    • 2016-11-02
    • 2014-01-26
    • 2016-06-08
    • 2020-08-12
    • 2021-02-11
    • 1970-01-01
    • 2015-06-26
    相关资源
    最近更新 更多