簡體   English   中英

如何獲取數組中的objectId的內容-Mongoose / NodeJs

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

我想用我的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 }
});

貓鼬的要求

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的內容:/像“名稱”,“別名” ...

我知道我可以寫兩個請求來獲取內容,但是它不是經過優化的:/

你能幫助我嗎 ?

謝謝,

您需要提供要在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));
    }
);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM