使用Node.js和Mongoose从JSON文件填充MongoDB中的引用集合

时间:2015-04-22 16:20:32

标签: mongoose mongoose-populate

我使用Node.js和Mongoose从JSON文件填充MongoDB中的引用集合

$ npm run styles

页面是从JSON文件很好地创建的,并且“站点”文档中的页面字段已填充但我只有一个ID。我的意思是我的JSON文件有2页,所以我得到

页面:“_ id123456”,“_ id123456”来自

var UserSchema = new Schema({
username: String,
sites : [{type: mongoose.Schema.Types.ObjectId, ref: 'Site' }], 
});

var SiteSchema = new Schema({
user : { type: String, ref: 'User' },
siteTitle: String, 
pages : [{type: mongoose.Schema.Types.ObjectId, ref: prefix + 'Page' }],
});

var PageSchema = new Schema({
site: { type: String, ref: 'Site' },
title: String,
});

exports.create = function(req, res, next) {
var user = new User(req.body);
user.save(function(err) { // create user 
    if (err) {
        return next(err);
    } else {
        var site = new Site({user: user.username, siteTitle: user.username});
        site.save(function(err) { // create website
            if (err) {
                return next(err);
            } else {
                user.sites.push(site); // push site'id in sites field in user
                user.save(); // save user after site'id has been push

                for (var i=0; i<basePages.length; i++) { // create pages from base.json file
                    var page = new Page(basePages[i]);
                    page.save(function(err) { // create page
                        if (err) {
                            return next(err);
                        } else {
                            site.pages.push(page);
                            site.save();
                        }
                    });
                   res.json(user);
                }
            }
        });
    };
});
};

1 个答案:

答案 0 :(得分:0)

这是我发现自己的解决方案:)只需在page.save函数中添加页面作为参数;

exports.create = function(req, res, next) {
var user = new User(req.body);
user.save(function(err) { // create user 
    if (err) {
        return next(err);
    } else {
        var site = new Site({user: user.username, siteTitle: user.username});
        site.save(function(err) { // create website
            if (err) {
                return next(err);
            } else {
                user.sites.push(site); // push site'id in sites field in user
                user.save(); // save user after site'id has been push
                for (var i=0; i<basePages.length; i++) { // create pages from base.json file
                    var page = new Page(basePages[i]);
                    page.save(function(err, **page**) { // create page
                        if (err) {
                            return next(err);
                        } else {
                            site.pages.push(**page**);
                            site.save();
                        };
                    });
                };
                res.json(user);
            };
        });
    };
});
};