NodeJS API:在Mongodb中默认通过“ Id”属性(而不是通过“ _id”)将文档查找到集合中

时间:2019-07-05 04:53:30

标签: node.js api mongoose

我想在我的架构中通过属性“ id”来检索文档,而不要使用Mongodb的默认“ _id”。

我想要这样的答复: https://sample-accounts-api.herokuapp.com/accounts/2

{
        attributes: {
          id: 2,
          user_id: 2,
          name: "Bカード",
          balance: 200
        }
      }

这是我的帐户模型:

var AccountSchema = new mongoose.Schema({
        id: {type: Number},
        user_id: {type: Number, ref: 'User'},
        name: String,
        balance: Number
});

这是我的Controller API:

const Account = require('../model/account');
exports.findOne = (req,res) => {
    Account
    .findById(???)
    .then(account => {
        if(!account) {
            return res.status(404).send({
                message: "Account not found with ID " 
            });
        }
        res.send(account);
    })
    .catch(err => {
        return res.status(505).send({
            message: "Something wrong retrieving account with Id "
        });
    })
}

2 个答案:

答案 0 :(得分:1)

    exports.findOne = (req,res) => {
    Account
    .findOne({'attributes.id':req.params.id})
    .then(account => {
        if(!account) {
            return res.status(404).send({
                message: "Account not found with ID " 
            });
        }
        res.send(account);
    })
    .catch(err => {
        return res.status(505).send({
            message: "Something wrong retrieving account with Id "
        });
    })
}

使用attributes.id并将其映射到您的req.params.id

答案 1 :(得分:1)

我解决了这个问题。

我的代码:

const Account = require('../model/account');

exports.findOne = (req,res) => {
Account
// Find a Account by "id" property and except the "_id" & "__v" field
.findOne({id:req.param("id")}, {_id: 0, __v: 0}) 
.then(account => {
    if(!account) {
        return res.status(404).send({
            message: "Account not found with ID " 
        });
    }
    res.send({'attributes':account});
})
.catch(err => {
    return res.status(505).send({
        message: "Something wrong retrieving account with Id "
    });
})

}