我想在我的架构中通过属性“ 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 "
});
})
}
答案 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 "
});
})
}