仅在当前不存在时才在mongoose中创建多个文档

时间:2014-04-18 03:06:36

标签: mongodb mongoose

我想知道是否要在mongoose中创建多个文档,但前提是它们目前不存在?从文档中,我发现下面的代码可以创建多个文档,但只是想知道如何确保它不会创建文档(如果它当前存在)?

特别是,如果一个文档已经存在,我希望创建当前未创建的其他文档(而不是整个创建操作失败)。

From Documentation
var array = [{ type: 'jelly bean' }, { type: 'snickers' }];
Candy.create(array, function (err, jellybean, snickers) {
  if (err) // ...
});

1 个答案:

答案 0 :(得分:1)

如文档中所述,.create()方法是一种快捷方式,用于为给定模型创建新文档,并且"保存"它到集合。这实际上就像更正式的.save()方法,但是以快捷方式表示。

你所描述的更类似于" upsert" MongoDB .update()方法的行为。哪个也可以适用于.findAndModify堂兄,或者特别是mongoose,.findOneAndUpdate()方法。

所以使用一些示例代码:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

mongoose.connect('mongodb://localhost/nodetest');

var candySchema = new Schema({
  type: String
});

var Candy = mongoose.model( "Candy", candySchema );

var array = [
  { type: 'jelly bean' },
  { type: 'snickers' },
  { type: 'mars' },
  { type: 'snickers' }
];

array.forEach(function(n) {

  Candy.findOneAndUpdate( n, n, { upsert: true }, function(err,doc) {
    console.log( doc );
  });

});

您会看到以下输出:

{ _id: 535088e2e4beaab004e6cd97, type: 'jelly bean' }
{ _id: 535088e2e4beaab004e6cd98, type: 'snickers' }
{ _id: 535088e2e4beaab004e6cd99, type: 'mars' }
{ _id: 535088e2e4beaab004e6cd98, type: 'snickers' }

注意到'窃笑'的第二个条目实际上是指已经创建的对象。

这是确保在指定"键"在查询条件中匹配。