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
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.