尝试使用填充将两个子集合关联到父集合
Trying to associate two children collections to a parent collection using populate
'我正在尝试在医生集合中包含一组患者 Objectid 和一组数据(有关医生的信息)objectid。这是代码的开头然后我迷路了。我想我想使用这样的东西 Doctor.find().populate('patients data')
。如果有人能告诉我如何访问这些信息那就太好了。
var express = require("express");
var app = express();
var mongoose = require("mongoose");
mongoose.connect("mongodb://localhost/population")
var doctorSchema = new mongoose.Schema({
name : String,
patients : [{type : mongoose.Schema.Types.ObjectId, ref : "Patient"}],
data : [{type : mongoose.Schema.Types.ObjectId, ref : "Data"}]
})
var patientSchema = new mongoose.Schema({
name : String
})
var dataSchema = new mongoose.Schema({
income : String
})
var Doctor = mongoose.model("Doctor",doctorSchema );
var Patient = mongoose.model("Patient", patientSchema);
var Data = mongoose.model("Data", dataSchema);
var doc1 = new Doctor({"name" : "doc1"})
doc1.save(doc1, function(err, doc){
if(err){
console.log(err)
}else{
console.log("saved")
}
})
app.listen(3000, function(){
console.log("listening on 3000");
})
要访问信息,app
应该能够接收请求;需要在 app
对象上定义 'get' 方法:
app.get('/:id', function(req, res) {
var doctorID = req.params.id;
Doctor
.findOne({_id: doctorID})
.populate('patients data')
.exec(function(err, doctor) {
if (err) throw err;
res.send(doctor);
});
});
'我正在尝试在医生集合中包含一组患者 Objectid 和一组数据(有关医生的信息)objectid。这是代码的开头然后我迷路了。我想我想使用这样的东西 Doctor.find().populate('patients data')
。如果有人能告诉我如何访问这些信息那就太好了。
var express = require("express");
var app = express();
var mongoose = require("mongoose");
mongoose.connect("mongodb://localhost/population")
var doctorSchema = new mongoose.Schema({
name : String,
patients : [{type : mongoose.Schema.Types.ObjectId, ref : "Patient"}],
data : [{type : mongoose.Schema.Types.ObjectId, ref : "Data"}]
})
var patientSchema = new mongoose.Schema({
name : String
})
var dataSchema = new mongoose.Schema({
income : String
})
var Doctor = mongoose.model("Doctor",doctorSchema );
var Patient = mongoose.model("Patient", patientSchema);
var Data = mongoose.model("Data", dataSchema);
var doc1 = new Doctor({"name" : "doc1"})
doc1.save(doc1, function(err, doc){
if(err){
console.log(err)
}else{
console.log("saved")
}
})
app.listen(3000, function(){
console.log("listening on 3000");
})
要访问信息,app
应该能够接收请求;需要在 app
对象上定义 'get' 方法:
app.get('/:id', function(req, res) {
var doctorID = req.params.id;
Doctor
.findOne({_id: doctorID})
.populate('patients data')
.exec(function(err, doctor) {
if (err) throw err;
res.send(doctor);
});
});