populate much filling level in the mongoose, nested fields filled?

When mongoose in memory if it is referenced in a multi-stage , when the query is filled reference field will be used populate, as follows:

Define a User, field friends have each their own collection of ObjectId.

// file: user-schema.js
let mongoose = require('mongoose')
let ObjectId = mongoose.Schema.Types.ObjectId

module.exports = new mongoose.Schema({
    name: String,
    friends: [{type: ObjectId, ref: 'User'}]
})
// file: user-model.js
let mongoose = require('mongoose')
let userSchema = require('./user-schema.js')

module.exports = mongoose.model('User', userSchema)

CommentSchema have defined a field from a User of the _id, as well as nested fields reply every field there is a document from and to all User's _id

// file: comment-schema.js
let mongoose = require('mongoose')
let ObjectId = mongoose.Schema.Types.ObjectId

module.exports = new mongoose.Schema({
    from: {type: ObjectId, ref: 'User'},
    content: String,
    reply: [
        {
            to: {type: ObjectId, ref: 'User'},
            from: {type: ObjectId, ref: 'User'},
            content: String
        }
    ]
})

Here begin the query.

// file: comment-model.js
let mongoose = require('mongoose')
let ObjectId = mongoose.Schema.Types.ObjectId

module.exports = mongoose.model('Comment', userSchema)
let Comment = require('./comment-model.js')

Comment.findOne({})
		.populate('from') // 填充from字段
		.populate('reply.to reply.from') // 填充reply字段下的to和from

Note: Fill in the reply to field and from the not mongoose official text populate chapter multistage packed in.

// file: comment-model.js
Coment.findOne({})
		.populate({path: 'from', populate: {path: 'friends'}})

Fields filled with friends from out of the field in the query results is a multi-stage filling.

Multi-level refers to the need to fill out the fields in the query data corresponding to the defined Schema. And fill type defined in the first query is comment-schema.js, whether it is from the following fields or reply to and from. The second query from the field in comment-schema.jsthe definition, but friends fields check out the document User is defined in the user-schema.js in.

My understanding is: accurate to say that the multi-stage needs to be filled after the field is filled appears . The field can not be said to be nested multi-level, at least I think so.

Published 48 original articles · won praise 52 · views 50000 +

Guess you like

Origin blog.csdn.net/letterTiger/article/details/84710937