晚的答案,但在定义架构时你也可以试试这个。
/**
* toJSON implementation
*/
schema.options.toJSON = {
transform: function(doc, ret, options) {
ret.id = ret._id;
delete ret._id;
delete ret.__v;
return ret;
}
};
注意ret
是JSON'ed对象,这不是猫鼬模型的实例。你将在对象散列上对它进行操作,而不使用getter/setter。
然后:
Model
.findById(modelId)
.exec(function (dbErr, modelDoc){
if(dbErr) return handleErr(dbErr);
return res.send(modelDoc.toJSON(), 200);
});
编辑:2015年2月
因为我没有提供一个解决缺少的toJSON(或toObject)方法(S)我会解释的区别我的使用示例和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);
});
我的例子:
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());
}
});
好的,它似乎是答案。 – 2013-01-04 14:50:27
不应该是:'JSON。stringify(users);'因为用'lean()'返回的文档是纯JS对象? – enyo 2013-01-09 14:30:23
是的,你是对的,谢谢。应该使用JSON.stringify(用户)。 – ecdeveloper 2013-10-20 11:13:17