猫鼬嵌套参考人口

时间:2016-03-16 17:02:10

标签: node.js mongodb mongoose-populate

我无法理解mongoose populate方法背后的一些概念。我首先使用嵌入式方法,但是,由于我担心数据和不同步文档的大量开销,我尝试将范例更改为 controller('PlaylistCtrl', function($scope, $stateParams, $sceProvider) { $sceProvider.enabled(false); //this will cause CORS vulnerabilities. $scope.playlistSet = [ [ { track: 'Iris', artist: 'Sleeping with the Sirens', video: 'http://www.youtube.com/watch?v=cyOqIKGbYkg'} ] $scope.id = $stateParams.playlistId;}); 其他文档。

我的架构类似于以下内容(删除了不相关的属性):

ref

现在我试图像这样var userSchema = mongoose.Schema({ name: {type: String, default:''}, favorites:{ users:[{type: Schema.Types.ObjectId, ref: this}], places:[{type: Schema.Types.ObjectId, ref: PlaceSchema}] } }); module.exports = mongoose.model('User', userSchema); User {/ p>}:

favorites

虽然这不会按预期工作,因为User.findOne({_id: currentUser}).exec(function(err, user){ console.log(user); if (err) throw err; if(!user){ console.log("can't find user"); }else{ // user found user.populate('favorites.users'); user.populate('favorites.places'); // do something to the 'user.favorites' object } }); user.favorites.users都未定义。

我认为我可以如上所述填充,但显然,事实并非如此。根据我的阅读,我必须遗漏一些指示(可能)user.favorites.places编辑文档的模型?这个流程对我来说很新鲜,我有点失落。

无论如何,我可以通过填充上面的查询结果来获得refusers的数组吗?我尝试placespopulate链接,但它也无法正常工作。有没有更好的方法来实现这个结果?

编辑:如果需要,在数据库中,exec文档显示为:

User

编辑:更多细节...我目前正在存储/删除像这样的引用ObjectIds(注意targetID是一个字符串):

{
  "_id": "56c36b330fbc51ba19cc83ff",
  "name": "John Doe",
  "favorites": {
    "places": [],
    "users": [
      "56b9d9a45f1ada8e0c0dee27"
    ]
  }
}

另外,我需要填充user.favorites.users.push({ _id: mongoose.Types.ObjectId(targetID)}); user.favorites.users.pull({ _id: mongoose.Types.ObjectId(targetID)}); users及其各自的文档以及,我认为在我原来的问题中可能并不清楚。

2 个答案:

答案 0 :(得分:1)

尝试:

User
.findOne({_id: currentUser})
.populate('favorites.users')
.populate('favorites.places')
.exec( function (err, user) {
  // user.favorites.users
  // user.favorites.places
});

答案 1 :(得分:0)

好吧,我通过适当关注文档(以及@DJeanCar' s(+ 1' d)帮助/指针)找出了我需要的东西。

Mongoose的docs关于跨多个级别填充,我已经达成了这个解决方案:

window.location.href

此外,据我所知,如果您需要在填充后过滤所需的文档字段,还可以在window.location.replace('https://www.google.com/');的选项中传递User.findOne({_id: currentUser}) .populate({path:"favorites.users", populate: "name"}) .populate({path:"favorites.places", populate: "name"}) .exec(function(err, user){ if(err) throw err; if(!user){ console.log("couldnt find source user"); }else{ // here, user.favorites is populated and I can do what I need with the data } });

希望这可以帮助有类似问题的人!

相关问题