簡體   English   中英

貓鼬填充查詢方法

[英]Mongoose Populate Method for Querying

我有兩個集合,其中一個集合包含一個鏈接字段,可在兩個集合之間建立關系。 我試圖弄清楚如何使用populate方法正確顯示來自兩個符合我的過濾條件的集合中的文檔。

這是我的兩個模型的設置。

圖片

var imageSchema = new Schema({
    pattern: { type: String, enum: ['Solid', 'Stripe', 'Plaid'] },
    color: { type: String, enum: ['Grey', 'Navy Blue', 'Black', 'Khaki', 'Brown'] },
    imageName: String,
    imageUrl: String,
    imageSource: String,
    descriptions_id: String
});

var Images = mongoose.model('Images', imageSchema);

module.exports = Images; 

內容描述

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var descriptionSchema = new Schema({
    _id: String,
    pattern: { type: String, enum: ['Solid', 'Stripe', 'Plaid'] },
    color: { type: String, enum: ['Grey', 'Navy Blue', 'Black', 'Khaki', 'Brown'] },
    body: String,
});

var Description = mongoose.model('Description', descriptionSchema);

module.exports = Description;

基本上,我想顯示所有與我的描述ID值匹配的圖像。 例如,我的描述具有_idnavy-blue 該值與圖像文檔的descriptions_id值相同。

這是適當的命令嗎?

Images.find({ pattern: "solid", color:"navy-blue", descriptions_id:"navy-blue"}).populate('images').populate('descriptions');

更新:

圖片和說明文檔示例

說明:

{
    "_id" : "navy-blue",
    "body" : "Lorem Impsum."
}

圖片:

{ "_id" : ObjectId("55f5c6db7f057f0dfdfasdff2cf1cd"), "pattern" : "stripe", "propercasePattern" : "Stripe", "color" : "navy-blue", "propercaseColor" : "Navy Blue", "imageUrl" : "https://s3.amazonaws.com/blue-shirt.jpg", "imageSource" : "source", "descriptions_id" : "navy-blue" }

我認為您已經優化了架構。 當您想用圖像集合填充“描述”時,為什么在兩個模式中都具有相同的字段,例如圖案,顏色。 如果要填充,則在定義圖像架構時必須引用descriptions集合。

var imageSchema = new Schema({
imageName: String,
imageUrl: String,
imageSource: String,
descriptions_id:{  type: Schema.ObjectId,
ref: 'Description'}
});

然后嘗試使用此查詢

 Images.find().populate({path:'descriptions_id',match:  {pattern:'solid',color:'navy-blue'}).exec(function(res){
 if(res){
   res = res.filter(function (doc) {
                    return doc.descriptions_id;
                });
         }
    })

讓我知道它是否對您有用。

暫無
暫無

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

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