【问题标题】:Populate array of object Id's from mongoose sub-schema从 mongoose 子模式填充对象 ID 的数组
【发布时间】:2018-06-11 23:28:38
【问题描述】:

我有架构

    var likedSchema = new Schema({
        counter: {type: Number, default: 0, required: true},
        user: {type: Array, default: [], ref: 'User'}
    });

上述架构包含与用户和计数器相关联的 ObjectId 的数量。

    var mySchema = new Schema({
        liked: likedSchema,
        name: {type: String, required: true}
    });

在上面的模式中,我使用了 likeSchema

        mongoose.model('MyModel', mySchema);

这是定义的两个架构。 在 likeSchema 中,我有多个用户记录的 objectId。

通过使用 mySchema,我想填充这些记录以获取所有用户的详细信息。

liked: {counter: 1, user:[{"name": 
"smith","_id":"5a437f06b2a00b28ecf217a9"},{"name": 
"john","_id":"5a437f06b2a00b28ecf21192"}];

我需要以上述格式显示数据,以及用户详细信息。 谁能帮我解决这个问题。

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    在likedSchema中:

    user: [{
        type: mongoose.Schema.Types.ObjectId,
        ref: "User"
    }]
    

    然后在查询数据库时,例如使用 findById,对其使用填充,如下所示:

    MySchema.findById({someId}).populate("liked.user").exec(err, foundObject){
        //if no error, then you have the object with a list of users in the liked object here.
        console.log(foundObject.liked); //obviously in your code, have an if (err) line before this 
    }
    

    【讨论】:

    • 然后将其标记为正确,以便认为问题已解决
    • @rakan316 我也有类似的问题,如果您有空闲时间可以帮助我。 Here my post about the problem
    • 太棒了,找到几个用户有用吗?我的意思是,例如:findById({}).populatefindById({here a query with several id... }).populate
    猜你喜欢
    • 2018-09-10
    • 2022-01-24
    • 2016-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-23
    • 2019-06-23
    • 2019-12-06
    相关资源
    最近更新 更多