alec wilson
alec wilson

Reputation: 176

Mongoose and Nodejs get the name of a user by there ids

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

Answers (2)

Pavel Barmin
Pavel Barmin

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:

  1. Pass callback function like
Users.findById(id, function (err, user) {
  console.log(user.name);
});
  1. Use .then() like with promise
Users.findById(id).then((user) => {
  console.log(user.name);
});
  1. Use async/await:
async function getUser(id) {
   const user = await Users.findById(id);
   console.log(user.name);
};

Upvotes: 1

eol
eol

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

Related Questions