Mongoose - 创建模型保存参考

时间:2022-04-04 19:44:16

In mongoose, is it possible to create a referenced document while saving the document it is being referenced in? I have tried the below but it does not seem to work for me.

在mongoose中,是否可以在保存引用的文档时创建引用文档?我已经尝试过以下但它似乎对我不起作用。

var Model1Schema = new Schema({ 
  foo: String,
  child: { ref: 'Model2', type: ObjectId }
});

var Model2Schema = new Schema({ 
  foo: String
});

mongoose.model('Model1', Model1Schema);
mongoose.model('Model2', Model2Schema);

var m = new (mongoose.model('Model1'));

m.set({
  foo: 'abc',
  child: {
    bar: 'cba'
  }
}).save();

1 个解决方案

#1


20  

Mongoose validation won't allow child to be created since it is a reference, so the second-best thing you can do is creating your own function to create an instance with the corrected child, that has already been saved. Something similar to this, I imagine..

Mongoose验证不允许创建子项,因为它是一个引用,因此您可以做的第二件事是创建自己的函数来创建一个已经保存的已更正子项的实例。与此类似的东西,我想..

var Model1Schema = new mongoose.Schema({ 
    foo: String,
    child: { ref: 'Model2', type: mongoose.Schema.ObjectId }
});

var Model2Schema = new mongoose.Schema({ 
    foo: String
});

var Model1 = mongoose.model('Model1', Model1Schema);
var Model2 = mongoose.model('Model2', Model2Schema);

function CreateModel1WithStuff(data, cb) {
    if (data.child) { // Save child model first
        data.child = Model2(data.child);
        data.child.save(function(err) {
            cb(err, err ? null : Model1(data));
        });
    } else { // Proceed without dealing with child
        cb(null, Model1(data));
    }
}

CreateModel1WithStuff({
    foo: 'abc',
    child: {
      bar: 'cba'
    }
}, function(err, doc) {
    doc.save();
});

#1


20  

Mongoose validation won't allow child to be created since it is a reference, so the second-best thing you can do is creating your own function to create an instance with the corrected child, that has already been saved. Something similar to this, I imagine..

Mongoose验证不允许创建子项,因为它是一个引用,因此您可以做的第二件事是创建自己的函数来创建一个已经保存的已更正子项的实例。与此类似的东西,我想..

var Model1Schema = new mongoose.Schema({ 
    foo: String,
    child: { ref: 'Model2', type: mongoose.Schema.ObjectId }
});

var Model2Schema = new mongoose.Schema({ 
    foo: String
});

var Model1 = mongoose.model('Model1', Model1Schema);
var Model2 = mongoose.model('Model2', Model2Schema);

function CreateModel1WithStuff(data, cb) {
    if (data.child) { // Save child model first
        data.child = Model2(data.child);
        data.child.save(function(err) {
            cb(err, err ? null : Model1(data));
        });
    } else { // Proceed without dealing with child
        cb(null, Model1(data));
    }
}

CreateModel1WithStuff({
    foo: 'abc',
    child: {
      bar: 'cba'
    }
}, function(err, doc) {
    doc.save();
});