Harry Kruger
Harry Kruger

Reputation: 317

Document.get on nested document returns undefined

When I use Document.get on a nested document it returns undefined, where as when I use Document.get with the full path it works

Example:

const PostsSchema = new mongoose.Schema({
    author: {
        name: String
    }
});

const Posts = mongoose.model('posts', PostsSchema);

const doc = new Posts({
    author: {
        name: 'Harry'
    }
});

console.log(doc.get('author.name'));
// "Harry"
console.log(doc.author.get('name'));
// undefined

Upvotes: 1

Views: 219

Answers (1)

Marcus Castanho
Marcus Castanho

Reputation: 143

I believe the difference between the two ways you've presented is related to the difference between Subdocuments and nested paths as explained in the official doc: Subdocuments versus Nested Paths

Comparing to the examples given, 'author' is not a Subdocuments of the 'Posts', it's a property defined in the Schema, therefore, the correct syntax, as presented in the official doc Document.prototype.get(), is to pass the path as a string (as the first way you typed):

doc.get(path,[type],[options])
  • path «String»
  • [type] «Schema|String|Number|Buffer|*» optionally specify a type for on-the-fly attributes
  • [options] «Object»
  • [options.virtuals=false] «Boolean» Apply virtuals before getting this path
  • [options.getters=true] «Boolean» If false, skip applying getters and just get the raw value

Upvotes: 1

Related Questions