我查了其他问题,包括这个问题但是我找不到解决我问题的答案。
通过显示引用并将模型类型定义为Schema.Types.ObjectId,我以mongoose 的官方文档中描述的相同方式定义了我的模型。他们来了:
故事模型.js
var storySchema = new Schema({
...
candidateParts: [{ type: Schema.Types.ObjectId, ref: 'StoryPart'}],
...
}, { usePushEach: true});
Run Code Online (Sandbox Code Playgroud)
storyPart_model.js
var storyPartSchema = new Schema({
...
storyId: { type:Schema.Types.ObjectId, ref: 'Story' },
...
}, { usePushEach: true});
Run Code Online (Sandbox Code Playgroud)
而且,我已经建立了这样的一个地方查询ObjectID = require('mongodb').ObjectID;和storyModel是通过故事传递storyController.js
这是我调用 populate 的方式:
StoryController.prototype.getCandidateParts = function (storyId, callback) {
var me = this;
const id = { '_id': ObjectID(storyId) };
me.storyModel.findOne(id).populate('candidateParts').exec(function(err,story) {
if (err) return callback(err, …Run Code Online (Sandbox Code Playgroud)