Mongoose - 在预保存挂钩中保存对象

时间:2018-01-20 11:06:08

标签: javascript node.js mongodb mongoose

我想创建documents,但这些文档包含urls,因此document结构如下所示:

const document = {
  name: 'some name',
  text: 'some text,
  file_type: 'file type',
  urls: [{
    path: 'some path',
    display_url: 'some path',
  }],
};

我创建了DocumentSchemaURLSchema,如下所示:

const DocumentSchema = new Schema({
  text: String,
  file_type: String,
  name: String,
  urls: [{ type: Schema.Types.ObjectId, ref: 'URL' }],
});

const URLSchema = new Schema({
  path: String,
  display_url: String,
});

现在我想创建多个文档,因此我将一组文档对象传递给Document.create

Document.create(documents, (err, documents) => {
   // ...
})

我想在文档保存之前创建URL,因此我创建了一个pre save钩子:

Document.pre('save', true, function (next, done) {
  console.log('Saving doc', this);
  // probably URL.insertMany(this.urls) ???
});

我的问题

this对象不包含urls个对象,但传递给documents的{​​{1}}数组中的对象有Document.create

在保存urls之前,我该怎么做才能创建URLs

1 个答案:

答案 0 :(得分:2)

您应该在pre

中插入DocumentSchema中间件
  DocumentSchema.pre('save', function(next){
      URL.insertMany(this.urls, function(err, res){
          if(err) throw err;
          next();
      })
  });

例如

  const Schema = mongoose.Schema;

  const DocumentSchema = new Schema({
    text: String,
    path: String,
    urls: [{ type: Schema.Types.ObjectId, ref: 'URL' }],
  });

  const URLSchema = new Schema({
    url: String,
    display_url: String,
    ref: Boolean,
  });

  const URL = mongoose.model('URL', URLSchema, 'urls');

  DocumentSchema.pre('save', function(next){
      URL.insertMany(this.urls, function(err, res){
          if(err) throw err;
          next();
      })
  });

  const Document = mongoose.model('Document', DocumentSchema, 'documents');

样本插入

  var u1 = new URL({url : 'www.google.com'});
  var d1 = new Document({text: 'test text', urls : [u1]})
  var u2 = new URL({url : 'www.google.com'});
  var d2 = new Document({text: 'test text', urls : [u2]})  
  Document.create([d1, d2], function(err, docs){
      if(err) console.log(err)
      console.log(docs)
  })