MongoDB:输出"id"而不是"_id" [英] MongoDB: output 'id' instead of '_id'

查看:85
本文介绍了MongoDB:输出"id"而不是"_id"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用猫鼬(节点),输出id而不是_id的最佳方法是什么?

I am using mongoose (node), what is the best way to output id instead of _id?

推荐答案

我在执行此操作的模型上创建toClient()方法.这也是重命名/删除您不想发送给客户端的其他属性的好地方:

I create a toClient() method on my models where I do this. It's also a good place to rename/remove other attributes you don't want to send to the client:

Schema.method('toClient', function() {
    var obj = this.toObject();

    //Rename fields
    obj.id = obj._id;
    delete obj._id;

    return obj;
});

这篇关于MongoDB:输出"id"而不是"_id"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆