为人口节省的猫鼬

时间:2016-02-26 17:32:14

标签: node.js express mongoose mongoose-populate mongoose-schema

我对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( ...

1 个答案:

答案 0 :(得分:1)

根据mongoose docs,有两种方法可以将子文件添加到父对象:

1)使用push()方法

2)使用create()方法

因此,我认为通过取消保存新的下载项目的操作可以略微简化您的代码:

function createDownload(req, res) {
    var dldata = req.body;

    Project.findOne({ _id : dldata._project }, function(err, project) {
        // handle error

        project._downloads.push(dldata);

        project.save(function(err) {
            // handle the result
        });
    });
}

function createDownload(req, res) {
    var dldata = req.body;

    Project.findOne({ _id : dldata._project }, function(err, project) {
        // handle error

        project._downloads.create(dldata);

        project.save(function(err) {
            // handle the result
        });
    });
}