2015-09-06 153 views
0

Node.js應用與Mongoose(Mongodb),有了這個代碼,我獲取用戶和他們的書:現在,我想取一個具有特別的書用戶貓鼬填充條件

Users.find({user_id: req.user.id}).populate('books').exec(..); 

。我這樣做:

Users.find({user_id: req.user.id}).populate('books',null,{bookname:"harry potter"}).exec(..); 

但它不起作用。有了這個,我的代碼獲取用戶的null價值的書籍,如果該條件匹配,返回它們而不是null。實際上,我的大部分用戶都擁有null的書籍價值。但我想要的是,如果該填充部分中的condioton不匹配,則根本不要返回該用戶的結果數組!

我該怎麼辦?我必須做另一個查詢或什麼結果我需要什麼?

回答

3

所有我能想到這裏是你在呼喚它錯了。除了您的.populate()參數看起來不正確之外,您不會在此顯示很多背景。

這是一個正確的房源爲重複的例子:

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

var thingSchema = new Schema({ 
    _id: Number, 
    name: String 
},{ _id: false }); 

var parentSchema = new Schema({ 
    name: String, 
    things: [{ type: Number, ref: 'Thing' }] 
}); 

var Thing = mongoose.model('Thing', thingSchema), 
    Parent = mongoose.model('Parent', parentSchema); 

mongoose.connect('mongodb://localhost/thingtest'); 

var things = { "one": 1, "two": 2, "three": 3 }; 

async.series(
    [ 
    function(callback) { 
     async.each([Thing,Parent],function(model,callback) { 
     model.remove({},callback); 
     },callback); 
    }, 
    function(callback) { 
     var parentObj = new Parent({ "name": "me" }); 
     async.each(
     Object.keys(things).map(function(key) { 
      return { "name": key, "_id": things[key] } 
     }), 
     function(thing,callback) { 
      var mything = new Thing(thing); 
      parentObj.things.push(thing._id) 
      mything.save(callback) 
     }, 
     function(err) { 
      if (err) callback(err); 
      parentObj.save(callback); 
     } 
    ); 
    }, 
    function(callback) { 
     console.log("filtered"); 
     var options = { 
     path: 'things', 
     match: { "name": { "$in": ['two','three'] } } 
     }; 

     Parent.find().populate(options).exec(function(err,docs) { 
     if (err) callback(err); 
     console.log(docs); 
     callback(); 
     }); 
    }, 
    function(callback) { 
     console.log('unfiltered'); 
     Parent.find().populate('things').exec(function(err,docs) { 
     if (err) callback(err); 
     console.log(docs); 
     callback(); 
     }) 
    } 
    ], 
    function(err) { 
    if (err) throw err; 
    mongoose.disconnect(); 
    } 
); 

這將始終如一地給出這樣的結果:

filtered 
[ { _id: 55ec4c79f30f550939227dfb, 
    name: 'me', 
    __v: 0, 
    things: 
    [ { _id: 2, name: 'two', __v: 0 }, 
     { _id: 3, name: 'three', __v: 0 } ] } ] 
unfiltered 
[ { _id: 55ec4c79f30f550939227dfb, 
    name: 'me', 
    __v: 0, 
    things: 
    [ { _id: 1, name: 'one', __v: 0 }, 
     { _id: 2, name: 'two', __v: 0 }, 
     { _id: 3, name: 'three', __v: 0 } ] } ] 

因此,需要在您的數據和通話好好看看。 .populate()調用需要匹配「路徑」,然後還提供「匹配」以查詢要填充的文檔。

1

使用elemMatch:

var title = 'Harry Potter'; 
Users.find({books: {$elemMatch: {name: title}}) 
.exec(processResults); 
+0

這不會有任何用處,其中「books」是一個ObjectId數組,用於引用的「Books」集合。這就是'.populate()'在這裏所暗示的用法。不是嵌入式文檔數組,而是這些文檔的ObjectId值。 –