如何在数组中获取objectId的内容- Mongoose / NodeJs

How to get content of objectId in an Array - Mongoose / NodeJs

本文关键字:Mongoose NodeJs objectId 数组 获取      更新时间:2023-09-26

我想用我的objectId(通过用户id找到)的内容获得我的标签的数组/对象。

userModel

var userSchema = new mongoose.Schema({
    pseudo : { type : String },
    fullname : { type : String },
    password : { type : String },
    email : { type : String },
    //tags : { type : Array },
    tags : [
        {
            objectId : { type : mongoose.Schema.Types.ObjectId, ref: 'tag'},
            completed : { type : Boolean }
        }
    ],
    dateCreation : { type : Date, default : Date.now }
});

tagModel

var tagSchema = new mongoose.Schema({
  name : { type : String },
  alias : { type : String },
  description : { type : String },
  dateCreation : { type : Date, default : Date.now }
});
<<p> 猫鼬请求/strong>
userModel.find({ _id : req.session.passport.user._id }).select('tags').populate('objectId', 'name alias').lean().exec(function (err, result) {
    console.log(JSON.stringify(result));
});

console.log

[
    {
        "_id":"538efe4a3bb9d97018b90ee4",
        "tags":[
                   {
                    "objectId":"538f25f7f4d621281b7376e9", 
                    "completed":false, 
                    "_id":"538f25f7f4d621281b7376ea"
                   }
        ]
    }
]

我想获得的内容objectId:/像'name', 'alias'…

我知道我可以写两个请求来获取内容,但它没有优化:/

你能帮我吗?

谢谢,

您需要提供要在populate调用中填充的字段的完整点符号路径:

userModel.find({ _id : req.session.passport.user._id })
    .select('tags')
    .populate('tags.objectId', 'name alias')
    .lean()
    .exec(function (err, result) {
        console.log(JSON.stringify(result));
    }
);