2015-09-06 151 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值。 –