0

这是我保存模型的 models.js 的代码

var mongoose = require('mongoose')
, Schema = mongoose.Schema;
var GroupSchema = new Schema({
    title      : String
    , elements   : [ElementSchema]
    , author     : String 
});
var ElementSchema = new Schema({
    date_added : Date
    , text       : String
    , author     : String 
});
mongoose.model('Group', GroupSchema);
exports.Group = function(db) {return db.model('Group');};

mongoose.model('Element', ElementSchema);
exports.Element = function(db) { return db.model('Element');
};

对我来说它看起来很清楚,但是当我这样做时

function post_element(req, res, next) {
Group.findOne({_id: req.body.group}, function(err, group) {
    new_element = new Element({author: req.body.author,
        date_added: new Date()});
        new_element.save();
        group.elements.push(new_element);
        group.save();
    res.send(new_element);
    return next();
})
}

我不明白为什么当我进入 Mongo 时,我有两个集合,一个称为带有嵌套组的 Groups(所以看起来不错),另一个集合称为 E​​lements。

为什么?它不应该被称为 Group 吗?没看懂,哪位大侠给我解释一下?

谢谢,克

4

2 回答 2

1

当您执行此行时:

new_element.save();

您正在将新创建的元素保存到 Elements 集合中。不要在元素上调用 save ,我认为你会得到你正在寻找的行为。

于 2012-05-29T23:18:26.990 回答
0

这是因为以下行:

mongoose.model('Element', ElementSchema);

这会在 mongoose 中注册一个模型,当您注册一个模型时,它将在 mongo 中创建自己的集合。你所要做的就是摆脱这条线,你会看到它消失了。

另一方面,使用以下方法导出模型,将文件设置为每个文件仅导出一个模型更加简洁和容易:

module.exports = mongoose.model('Group', GroupSchema);

希望这可以帮助!

于 2012-05-30T13:58:17.713 回答