Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
124 views
in Technique[技术] by (71.8m points)

javascript - 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
question from:https://stackoverflow.com/questions/65891756/document-get-on-nested-document-returns-undefined

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...