簡體   English   中英

在集合中查找嵌套(嵌入)object

[英]find nested (embedded) object in the collection

當我在 StackOverflow 上解決我的問題時,我注意到之前也有人問過同樣的問題,但他們都沒有得到好的回應或實際答案。

Mongoose 在嵌套 Object 上查找一個

如何在文檔中找到嵌套對象?

回到我的問題:我想找到嵌套在架構中的 object。 嘗試 findMany 給出所有對象,而 findOne 只給出第一個對象,但我想要其 id 通過 req.body.checkbox 傳遞的特定對象。 我的 JS 代碼就像..

    app.post("/data", uploads, function (req, res) {
User.findById(req.user.id, function (err, foundUser) {
    if (err) {
      console.log(err);
    } else {
      if (foundUser) {

        var checkedBox = req.body.checkbox;
console.log(checkedBox);
User.findMany({_id:foundUser._id},{comments:{$elemMatch:{_id:checkedBox}}} ,function(err,checkedobj){

  if(err){
    console.log(err);
  }
  else{
  console.log(checkedobj.comments);




    if (Array.isArray(checkedobj.comments)) {
      res.render("checkout",{SIMG: checkedobj.comments});
    } else {
      res.render("checkout",{SIMG: [checkedobj.comments]});
    }

  }
})

      }
    }
  });
});

這是我的架構,供參考

 const commentSchema = new mongoose.Schema({
  comment: String,
  imagename: String,
    permission:{type:Number,default:0},
});

const Comment = new mongoose.model("Comment", commentSchema);

const userSchema = new mongoose.Schema({
  firstname: String,
  lastname: String,
  email: String,
  password: String,
  comments: [commentSchema],
  permission:{type:Number,default:0},
});

userSchema.plugin(passportLocalMongoose);

const User = new mongoose.model("User", userSchema);

例子

{ 
    "_id" : ObjectId("5ec3f54adfaa1560c0f97cbf"), 
    "firstname" : "q", 
    "lastname" : "q", 
    "username" : "q@q.com", 
    "salt" : "***", 
    "hash" : "***", 
    "__v" : NumberInt(2), 
    "comments" : [
        {
            "permission" : NumberInt(0), 
            "_id" : ObjectId("5ec511e54db483837885793f"), 
            "comment" : "hi", 
            "imagename" : "image-1589973477170.PNG"
        }
    ], 
    "permission" : NumberInt(1)
}

當我檢查 3 個復選框時,console.log(checkBox) 日志:

[
  '5ec543d351e2db83481e878e',
  '5ec589369d3e9b606446b776',
  '5ec6463c4df40f79e8f1783b'
]

但是 console.log(checkedobj.comments) 只給出了一個 object。

[
  {
    permission: 0,
    _id: 5ec543d351e2db83481e878e,
    comment: 'q',
    imagename: 'image-1589986259358.jpeg'
  }
]

當您想要一個數組中的多個匹配元素時,您應該使用$filter聚合運算符

作為預防措施,首先檢查 req.body.checkbox 是否為數組並將其轉換為 ObjectIds 數組

app.post("/data", uploads, function (req, res) {
var ObjectId = mongoose.Types.ObjectId;
User.findById(req.user.id, function (err, foundUser) {
    if (err) {
      console.log(err);
    } else {
      if (foundUser) {

var checkedBox = req.body.checkbox;
if (!Array.isArray(checkedBox)) {
    checkedBox = [checkedBox]
}
console.log(checkedBox);
var checkedBoxArray = checkedBox.map(id => ObjectId(id))
User.aggregate([
   {$match: {_id: foundUser._id}},
   {
      $project: {
         comments: {
            $filter: {
               input: "$comments",
               as: "comment",
               cond: { $in: [ "$$comment._id", checkedBoxArray ] }
            }
         }
      }
   }
],function(err,checkedobj){

  if(err){
    console.log(err);
  }
  else{
  console.log(checkedobj[0].comments);




    if (Array.isArray(checkedobj[0].comments)) {
      res.render("checkout",{SIMG: checkedobj[0].comments});
    } else {
      res.render("checkout",{SIMG: [checkedobj[0].comments]});
    }

  }
})

      }
    }
  });
});

工作示例 - https://mongoplayground.net/p/HnfrB6e4E3C

上面的示例將僅返回 2 條與 id 匹配的評論

您可以使用findById()方法,這里提供了更多關於它的文檔

您可以使用類似這樣的內容通過 object id 進行搜索:-

var id = "123";
userSchema.findById(id, function (err, user) { ... } );

希望這可以幫助!

暫無
暫無

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

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