Xun Zhang
Xun Zhang

Reputation: 3

Mongoose: From an array of objects in model, extract value of a property as array

I have a schema of users, contains books, and I want to get the book list of one user

var userSchema = new Schema({
    id: {
        type: String,
        unique: true,
        required: true
    },
    gender: String,
    firstName: String,
    lastName: String,
    books: [{
        id: String
        title: String
        author: String
    }]

});

For example,

[{id: "1",
  gender: "Male",
  firstName: "Alan",
  lastName: "Brown",
  books: [
    { id: "ISN001",
      title: "Programming From Beginer to Give Up",
      author: "Someone"
    },
    { id: "ISN002",
      title: "Introduction to Databases",
      author: "BetaCat"
    }
  ]
},
{ id: "2",
  gender: "Female",
  firstName: "Cynthia",
  lastName: "Durand",
  books: [
    { id: "ISN003",
      title: "How to Play with Your Cat",
      author: "UrCat"
    },
    { id: "ISN004",
      title: "Greek Mythology",
      author: "Heracles"
    }
  ]
}]

I can get the user id by req.params.user_id, and return the book list array of this user. For example, I want ["Programming From Beginer to Give Up","Introduction to Databases"] if I get user_id 1. I try to do this by

var getBookList = (req, res) => {
    User.find(req.params.user_id, (err, user) => {
        var books = user.map((item) => {return item.title;});
    });
}

But doesn't work, because map is not a function for user.

Upvotes: 0

Views: 609

Answers (2)

nanobar
nanobar

Reputation: 66315

User is an object, you want to map the books array inside it.

const books = user.books.map(book => book.title)

Also change find to findById as you only want 1 record.

When in doubt put a console.log in there and see if the value is what you expect.

Upvotes: 1

Sudhakar
Sudhakar

Reputation: 585

User.find({id:req.params.user_id}, (err, user) => {
    var books = user.map((item) => {return item.title;});
});

Try the above one

Upvotes: 0

Related Questions