将Mongoose docs转换为json

Tra*_*Liu 63 json document object mongoose node.js

我以这种方式将jongoose docs作为json返回:

UserModel.find({}, function (err, users) {
    return res.end(JSON.stringify(users));
}
Run Code Online (Sandbox Code Playgroud)

但是,用户.__ proto__也被退回了.没有它我怎么能回来?我尝试了这个,但没有奏效:

UserModel.find({}, function (err, users) {
    return res.end(users.toJSON());    // has no method 'toJSON'
}
Run Code Online (Sandbox Code Playgroud)

ecd*_*per 133

您也可以尝试mongoosejs的lean():

UserModel.find().lean().exec(function (err, users) {
    return res.end(JSON.stringify(users));
}
Run Code Online (Sandbox Code Playgroud)

  • 不应该是:`JSON.stringify(users);`因为用`lean()`返回的文档是普通的JS对象? (9认同)
  • 请注意,“lean()”会去除虚拟属性 (3认同)

eAb*_*Abi 47

迟到的答案,但您也可以在定义架构时尝试此操作.

/**
 * toJSON implementation
 */
schema.options.toJSON = {
    transform: function(doc, ret, options) {
        ret.id = ret._id;
        delete ret._id;
        delete ret.__v;
        return ret;
    }
};
Run Code Online (Sandbox Code Playgroud)

请注意,这ret是JSON的对象,它不是猫鼬模型的实例.你可以在对象哈希上操作,没有getter/setter.

然后:

Model
    .findById(modelId)
    .exec(function (dbErr, modelDoc){
         if(dbErr) return handleErr(dbErr);

         return res.send(modelDoc.toJSON(), 200);
     });
Run Code Online (Sandbox Code Playgroud)

编辑:2015年2月

因为我没有提供缺少的toJSON(或toObject)方法的解决方案,所以我将解释我的用法示例和OP的用法示例之间的区别.

OP:

UserModel
    .find({}) // will get all users
    .exec(function(err, users) {
        // supposing that we don't have an error
        // and we had users in our collection,
        // the users variable here is an array
        // of mongoose instances;

        // wrong usage (from OP's example)
        // return res.end(users.toJSON()); // has no method toJSON

        // correct usage
        // to apply the toJSON transformation on instances, you have to
        // iterate through the users array

        var transformedUsers = users.map(function(user) {
            return user.toJSON();
        });

        // finish the request
        res.end(transformedUsers);
    });
Run Code Online (Sandbox Code Playgroud)

我的例子:

UserModel
    .findById(someId) // will get a single user
    .exec(function(err, user) {
        // handle the error, if any
        if(err) return handleError(err);

        if(null !== user) {
            // user might be null if no user matched
            // the given id (someId)

            // the toJSON method is available here,
            // since the user variable here is a 
            // mongoose model instance
            return res.end(user.toJSON());
        }
    });
Run Code Online (Sandbox Code Playgroud)

  • 这是最好的方式. (3认同)
  • @OMGPOP是的我确定我使用的是toJSON方法.OP的使用示例和我的之间的区别在于OP的问题是返回的`users`变量是一个mongoose实例的数组.您必须遍历数组并在每个实例上调用toJSON方法.在我的例子中,我使用findById方法直接将找到的mongoose实例传递给回调函数.然后,您可以直接在此实例上调用toJSON(或toObject)方法. (2认同)

Jam*_*son 24

首先,尝试toObject()而不是toJSON()

其次,你需要在实际的文档而不是数组上调用它,所以也许尝试更烦人的东西:

var flatUsers = users.map(function() {
  return user.toObject();
})
return res.end(JSON.stringify(flatUsers));
Run Code Online (Sandbox Code Playgroud)

这是一个猜测,但我希望它有所帮助


Fab*_*rra 13

model.find({Branch:branch},function (err, docs){
  if (err) res.send(err)

  res.send(JSON.parse(JSON.stringify(docs)))
});
Run Code Online (Sandbox Code Playgroud)


Tra*_*Liu 6

我发现我犯了一个错误.根本不需要调用toObject()或toJSON().问题中的__proto__来自jquery,而不是mongoose.这是我的测试:

UserModel.find({}, function (err, users) {
    console.log(users.save);    // { [Function] numAsyncPres: 0 }
    var json = JSON.stringify(users);
    users = users.map(function (user) {
        return user.toObject();
    }
    console.log(user.save);    // undefined
    console.log(json == JSON.stringify(users));    // true
}
Run Code Online (Sandbox Code Playgroud)

doc.toObject()从doc中删除doc.prototype.但它在JSON.stringify(doc)中没有任何区别.在这种情况下不需要它.