我正在努力寻找关于猫鼬儿童人口的例子或文件 .
http://mongoosejs.com/docs/populate.html
在他们的文档上:
var mongoose = require('mongoose')
, Schema = mongoose.Schema
var personSchema = Schema({
_id : Number,
name : String,
age : Number,
stories : [{ type: Schema.Types.ObjectId, ref: 'Story' }]
});
var storySchema = Schema({
_creator : { type: Number, ref: 'Person' },
title : String,
fans : [{ type: Number, ref: 'Person' }]
});
var Story = mongoose.model('Story', storySchema);
var Person = mongoose.model('Person', personSchema);
这是有道理的,一个人可以有很多故事,因此有“父母”字段“故事”,其中列出了所有故事 .
我正在努力理解的是你如何将故事推入人物模式 .
例如,我有 assignment schema :
var mongoose = require ( 'mongoose' ),
Schema = mongoose.Schema;
var assignmentSchema = new Schema (
{
_id: String,
assignName: String,
modInsID: [{ type: Schema.Types.Number, ref: 'ModuleInst' }],
studentAssigns: [{type: Schema.Types.ObjectId, ref: 'StudentAssign' }]
}
);
module.exports = mongoose.model ( 'Assignment', assignmentSchema );
studentAssigns
存储 studentAssigns
的所有id,然后可以与 .pre
中间件一起用于级联删除 .
那么现在我的StudentAssign架构:
var mongoose = require ( 'mongoose' ),
autoIncrement = require ( 'mongoose-auto-increment' ),
Schema = mongoose.Schema;
var connection = mongoose.createConnection("************");
autoIncrement.initialize(connection);
var studentAssignSchema = new Schema (
{
assID: [{ type: Schema.Types.String, ref: 'Assignment' }],
studentID: [{ type: Schema.Types.Number, ref: 'Student' }]
}
);
var StudentAssign = connection.model('StudentAssign', studentAssignSchema);
module.exports = mongoose.model ('StudentAssign', studentAssignSchema );
你可以看到它已经引用了' Assignment
'
这是我的api代码:
studentAssign POST:
router.route('/student-assignment').post( function(req, res) {
var studentAssign = new StudentAssign();
studentAssign.assID = req.body.assID;
studentAssign.studentID = req.body.studentID;
studentAssign.save(function(err, studentAssign) {
if(err) console.log(err);
res.status(200).json(studentAssign);
});
})
所以's the part I am confused at where would I push the ' studentAssign
' into ' Assignment
' schema' s'_280209_数组?
这是我目前的api json回调:
[
{
"_id": "As 1",
"assignName": "Software Implementation",
"__v": 0,
"studentAssigns": [],
"modInsID": [
{
"_id": 22,
"semester": "TRI 3",
"year": 2016,
"__v": 0,
"modID": [
111
]
}
]
}
]
文档只是没有说清楚,因为他们只是显示:
aaron.stories.push(story1); aaron.save(callback);
没有解释?
我试过了: var assignment = new Assignment(); assignment.studentAssigns.push(studentAssign);
并没有存储任何东西?
2 回答
你建模状态:
我认为从你的代码中你不想在assID中存储多个作业,而在studentID中存储多个学生 . 将模型修改为
您的保存代码可以保持不变 .
如果您确实要存储多个分配,则需要将它们推入assID数组;-)