简体   繁体   中英

pulling data from one mongodb collection into another

I have created a mongodb collection for a list of drinks The schema is below. 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/ . 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. If you uncomment drinkWant array and fill it with Drink _id's then you should be able to .populate() your results.

You simply just have to chain .populate() after running a query. For example:

myDrink.find({name: "someName"}).populate('drinkWant')
   .exec(function(err, results) {
      console.log(results);
});

For more information see here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM