[英]pulling data from one mongodb collection into another
I have created a mongodb collection for a list of drinks The schema is below. 我为饮料清单创建了一个mongodb集合。该模式如下。 In it I have made a drink list that users can choose from. 在其中,我列出了用户可以选择的饮料清单。
var drinkSchema = mongoose.Schema({
name: String,
date: {
type:Date,
// default: new Date()
default: Date.now()
},
caffeineLevel: String
});
var Drink = mongoose.model('Drink',drinkSchema);
module.exports = Drink;
I also created a second schema for users of my app. 我还为我的应用程序的用户创建了第二个架构。 Ideally the user would be able to move data into this schema by selecting a drink from the other schema. 理想情况下,用户将能够通过从其他模式中选择饮料来将数据移动到该模式中。 This schema would be unique to each user. 该方案对于每个用户而言都是唯一的。
var mongoose = require('mongoose');
var myDrinkSchema = mongoose.Schema({
name: String,
date: {
type:Date,
default: Date.now()
},
caffeineLevel: String
// drinkWant: [{type:mongoose.Schema.Types.ObjectId,ref:'Drink'}]
});
var myDrink = mongoose.model('myDrink',myDrinkSchema);
module.exports = myDrink;
I apologize that I do not have more knowledge of the matter. 抱歉,我对此事一无所知。 I searched through the documents and came across data modeling http://docs.mongodb.org/manual/core/data-model-design/ . 我搜索了文档,并发现了数据建模http://docs.mongodb.org/manual/core/data-model-design/ 。 But this did not seem to have a specific answer. 但这似乎没有特定的答案。
Is it possible to do this in a schema method? 是否可以在模式方法中执行此操作?
You have it right, however just because you specify a reference to another collection doesn't mean mongoose will populate it for you. 您说对了,但是仅仅因为您指定了对另一个集合的引用并不意味着猫鼬会为您填充它。 You actually have to specify which field/s you want to populate and it will populate those fields based on the ref
of that field in the schema. 实际上,您必须指定要填充的字段,然后它将根据架构中该字段的ref
填充这些字段。 If you uncomment drinkWant
array and fill it with Drink
_id's then you should be able to .populate()
your results. 如果您取消注释drinkWant
数组并用Drink
_id填充它,那么您应该可以.populate()
您的结果。
You simply just have to chain .populate()
after running a query. 您只需要在运行查询后链接.populate()
。 For example: 例如:
myDrink.find({name: "someName"}).populate('drinkWant')
.exec(function(err, results) {
console.log(results);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.