【问题标题】:Nested models mongoose with nodejs generates duplicates嵌套模型 mongoose 与 nodejs 生成重复
【发布时间】:2012-05-30 21:58:17
【问题描述】:

这是我保存模型的 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 吗? 没看懂,哪位大侠给我解释一下?

谢谢, g

【问题讨论】:

    标签: node.js mongoose


    【解决方案1】:

    当你执行这一行时:

    new_element.save();
    

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

    【讨论】:

    • 但在这种情况下,拥有两个独立的架构有什么意义?
    • 似乎在 Mongoose 中,如果您想要架构中的对象数组,则必须使用架构定义这些对象(或者是内置架构类型之一)。
    【解决方案2】:

    因为下面这行:

    mongoose.model('Element', ElementSchema);
    

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

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

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

    希望这会有所帮助!

    【讨论】:

      猜你喜欢
      • 2017-07-06
      • 2013-11-06
      • 2013-03-25
      • 2018-11-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-26
      • 1970-01-01
      相关资源
      最近更新 更多