在我的第一个项目上工作并且已经被困了几天了。
我试图填充一个包含啤酒厂信息的对象和来自Beer模型的单个相应啤酒。
models.js
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var beerSchema = Schema({
breweryName: String,
beer: [{
beerName: String
}]
});
var draftlistSchema = Schema ({
userName: String,
tap: [{
tapNo: Number,
_tapBeer: { type: Schema.Types.ObjectId, ref: 'Beer' },
tapStatus: String
}]
});
var Draftlist = mongoose.model('Draftlist', draftlistSchema);
var Beer = mongoose.model('Beer', beerSchema);
module.exports = {
Draftlist: Draftlist,
Beer: Beer
}
route.js
var getDraftlist = function(user, callback) {
models.Draftlist.findOne({ 'userName': user }).populate( {
path: 'tap._tapBeer',
model: 'Draftlist'
}).exec(function(err, draftlist) {
// console.log(draftlist.tap)
console.log(draftlist);
callback(draftlist);
});
};`
我使用当前代码返回null。理想情况下,我希望返回的对象看起来像 -
{
breweryName: Some Brewery,
beer: {// Beer object that was referenced by Id //}
}
Draftlist对象w / null return
{ _id: 590bd0615a190204fca6d467,
userName: 'A New User1',
__v: 1,
tap:
[ { tapNo: 1,
_tapBeer: null,
tapStatus: 'onTap',
_id: 590bd0615a190204fca6d46d },
{ tapNo: 2,
_tapBeer: null,
tapStatus: 'onTap',
_id: 590bd0615a190204fca6d46c },
{ tapNo: 3,
_tapBeer: null,
tapStatus: 'onTap',
_id: 590bd0615a190204fca6d46b },
{ tapNo: null,
_tapBeer: null,
tapStatus: 'Cellar',
_id: 590bd0615a190204fca6d46a },
{ tapNo: null,
_tapBeer: null,
tapStatus: 'Cellar',
_id: 590bd0615a190204fca6d469 },
{ tapNo: null,
_tapBeer: null,
tapStatus: 'Cellar',
_id: 590bd0615a190204fca6d468 },
{ _tapBeer: null,
tapStatus: 'Cellar',
_id: 590bd0735a190204fca6d470 } ] }
啤酒对象
{ breweryName: 'Beachwood',
_id: 590bd3f1ed13510514405cba,
beer: [ { beerName: 'IPA', _id: 590bd3f1ed13510514405cbb } ] }
答案 0 :(得分:0)
const
mongoose = require('mongoose'),
deepPopulate = require('mongoose-deep-populate')(mongoose);
Schema = mongoose.Schema;
const
BeerSchema = Schema({
breweryName: Schema.Types.String,
beer: [{
beerName: Schema.Types.String
}]
}),
DraftlistSchema = Schema ({
userName: Schema.Types.String,
tap: [{
tapNo: Schema.Types.Number,
_tapBeer: {
type: Schema.Types.ObjectId,
ref: 'Beer'
},
tapStatus: Schema.Types.String
}]
});
DraftlistSchema.plugin(deepPopulate);
var Draftlist = mongoose.model('Draftlist', DraftlistSchema);
var Beer = mongoose.model('Beer', BeerSchema);
module.exports = {Draftlist, Beer};
用法:
const getDraftlist = (userName, callback) => {
models
.Draftlist
.findOne({
userName
})
.deepPopulate('tap._tapBeer')
.exec((err, draftlist) => {
console.log(draftlist);
callback(draftlist);
});
};
或:
const Draftlist = models.Draftlist;
const getDraftlist = (userName, callback) => {
Draftlist
.findOne({
userName
})
.exec((err, draftlist) => {
Draftlist
.deepPopulate(
draftlist, 'tap._tapBeer',
(err, draflist) => {
console.log(draftlist);
callback(draftlist);
});
});
};