一般来说,我是 Mongoose 和 Nodejs 开发的新手,我对如何正确设置保存记录有点困惑。这是我的两个模式:
下载
var mongoose = require("mongoose");
var Schema = mongoose.Schema;
var downloadSchema = Schema({
title : String,
description : String,
_project : { type: Schema.Types.ObjectId, ref: 'Project' }
});
module.exports = mongoose.model('Download', downloadSchema);
项目
...
var projectSchema = Schema({
name : String,
url : String,
pwd : String,
_downloads : [{type: Schema.Types.ObjectId, ref: 'Download' }]
});
module.exports = mongoose.model('Project', projectSchema);
这似乎工作正常。该文档解释了我保存下载和链接项目的用例,但我不确定如何正确填充Project._downloads
. 这是我所做的:
快速路线处理程序:
function createDownload(req, res) {
// the Project Id is passed in the req.body as ._project
var dldata = req.body;
Project.findOne({ _id : dldata._project }, function(err, project) {
var dload = new Download(dldata);
dload.save( function (err, download) {
project._downloads.push(download._id);
project.save( function(err){
var msg = {};
if(err) {
msg.status = 'error';
msg.text = err;
}else {
msg.status = 'success';
msg.text = 'Download created successfully!';
}
res.json(msg);
});
});
});
}
这对我来说似乎过于复杂。我应该手动push
输入._downloads
数组,还是 Mongoose 应该根据架构在内部处理?有没有更好的方法来实现它,以便我可以做到:
Download.find().populate('_project').exec( ...
也:
Project.findOne({_id : _projectId}).populate('_downloads').exec( ...