Reputation: 176
I am new to Mongoose and couldn't find an answer elsewhere.
I have a user schema like this:
const userSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
email: {
type: String,
required: true
},
password: {
type: String,
required: true
},
date: {
type: Date,
default: Date.now
},
admin: {
type: Boolean,
default: true
},
writer: {
type: Boolean,
default: true
},
producer: {
type: Boolean,
default: true
}
})
And I want to get someone name by their _id
I have this: Users.findById(posts.userID).schema.obj.name
but it obviously doesn't return a name, thanks!
Upvotes: 0
Views: 1705
Reputation: 63
Any request to mongo via mongoose is asynchronus. So .findById method return promise-like object. You need to wait for result via one of three ways:
Users.findById(id, function (err, user) {
console.log(user.name);
});
Users.findById(id).then((user) => {
console.log(user.name);
});
async function getUser(id) {
const user = await Users.findById(id);
console.log(user.name);
};
Upvotes: 1
Reputation: 24555
findById
returns a single document containing the actual values for the properties you've defined in your schema. So if you're just interested in getting the name from the resulting document you can do:
const user = await Users.findById(posts.userID);
const name = user.name;
Upvotes: 1