Mongoose 推送到参考模型后如何保存?

Mongoose 推送到参考模型后如何保存?,mongoose,Mongoose,将数据推送到模型后,尝试保存模型时出现问题: 以下是模式: var ClientSchema = new Schema({ email: {type: String, required: '{PATH} is required!', unique: 'This email already exists!'}, name: String, nick: String, domains: [{ type: Schema.Types.ObjectId, ref: 'Dom

将数据推送到模型后,尝试保存模型时出现问题: 以下是模式:

var ClientSchema = new Schema({
    email: {type: String, required: '{PATH} is required!', unique: 'This email already exists!'},
    name: String,
    nick: String,
    domains: [{ type: Schema.Types.ObjectId, ref: 'Domain' }],
    hosting: [{ type: Schema.Types.ObjectId, ref: 'Hosting'}]
});

var DomainSchema = new Schema({
    name: {type: String, required: '{PATH} is required'},
    startDate: {type: Date, required: '{PATH} is required'},
    endDate: {type: Date, required: '{PATH} is required'},
    realPrice: {type: Number, required: '{PATH} is required'},
    billedPrice: {type: Number, required: '{PATH} is required'}
});
这是控制器的一部分:

...

         Client.findOne({_id: req.params.client_id},function(err,client) {

            var domain = new Domain({
                name: req.body.name,
                startDate: req.body.startDate,
                endDate: req.body.endDate,
                realPrice: req.body.realPrice,
                billedPrice: req.body.billedPrice
            });
            domain.save(function(err) {
                console.log(domain._id);
            });
                        cli.domains.push(domain._id);
            client.save(function(err,cli) {

                // That's the one that makes it possible to save
                // client.save();
            });

            res.redirect("/"); 
        });

...
现在,, 如果在一个
client.save(..)
中保持原样,则域会被保存,它会被推送,但客户端不会被保存。 如果我取消对另一个
client.save()
的注释,则所有内容都会按应有的方式保存(我猜)。 那么问题又来了,为什么我要存两次钱? 我是不是错过了一些很简单的东西? 别误会我的意思——这是可行的,但我只需要理解它;) 提前谢谢你的帮助


更新/解决方案


我遇到的所有问题都是因为在我的ubuntu机器上安装了旧版本(2.4.9)的mongodb,并且与mongodb使用的文档版本控制存在一些冲突。我在另一台机器上检查了相同的代码,一切正常。这就是为什么我重新检查并安装了更新的mongodb,同时清理了实际的db,使一切正常,当然也正常工作;)

Mongodb本质上是异步的。您需要在domain.save的回调下移动client.save()

编辑

我很快就尝试了你的问题,对我来说效果很好


检查这个

这是我一开始尝试的,但是mongo(ose)发现了这个错误:
{[MongoError:Field name duplication not allowed with modifiers]name:'MongoError',err:'Field name duplication not allowed with modifiers',code:10150,n:0,connectionId:333,ok:1}
请再次检查我的代码-我使用了cli,但它应该是客户端。我注意到了它,并在尝试之前进行了更改。我尝试了您的查询。为我工作很好。检查我添加到answeradd控制台的链接添加到每个步骤,我相信你会发现问题。我注意到的另一件事是,不要认为这会导致很多问题,但仍要检查它-您使用了这个“\u client:client.id”,但您的域架构没有“\u client”字段+1,用于更新/解决方案
Client.findOne({_id: req.params.client_id},function(err,client) {

    var domain = new Domain({
        _client: client.id,
        name: req.body.name,
        startDate: req.body.startDate,
        endDate: req.body.endDate,
        realPrice: req.body.realPrice,
        billedPrice: req.body.billedPrice
    });

    domain.save(function(err, result) {
        client.domains.push(result._id);
        client.save();
    });

    res.redirect("/"); 
});