Reputation: 41
I want to retrieve a document by property "id" in my schema, not use "_id" default of Mongodb.
I want to have response when I request like that: https://sample-accounts-api.herokuapp.com/accounts/2
{
attributes: {
id: 2,
user_id: 2,
name: "Bカード",
balance: 200
}
}
It's my Account Model:
var AccountSchema = new mongoose.Schema({
id: {type: Number},
user_id: {type: Number, ref: 'User'},
name: String,
balance: Number
});
And here is my 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 "
});
})
}
Upvotes: 1
Views: 141
Reputation: 41
I resolved this issue.
My code:
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 "
});
})
}
Upvotes: 1
Reputation: 1499
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 "
});
})
}
use attributes.id
and map it against your req.params.id
.
Upvotes: 1