使用mongoose将多个不存在的文档插入MongoDB

时间:2018-04-10 19:13:34

标签: javascript mongodb mongoose

我想保存多个文档,这些文档是在哈希符号'#'指示的帖子上找到的标签。我有一个数组中的标签。例如:

var tags = ['banana', 'apple', 'orange', 'pie']

我遍历它们并转换为文档对象(将它们插入到DB中)。问题是我只想在以前从未插入过的文档中插入。如果在我想要将插入文档的userCounter属性增加一个之前插入它。

var tags = ['banana', 'apple', 'pie', 'orange'];

var docs = tags.map(function(tagTitle) {
  return {
    title: tagTitle,
    // useCounter: ??????????
  };
});

var Hashtag = require('./models/Hashtag');

/**
* it creates multiple documents even if a document already exists in the collection,
* I want to increment useCounter property of each document if they exist in the collection;
* not creating new ones.
* for example if a document with title ptoperty of 'banana' is inserted before, now increment
* document useCounter value by one. and if apple never inserted to collection, create a new document 
* with title of 'apple' and set '1' as its initial useCounter value
*/

Hashtag.create(docs)
.then(function(createdDocs) {

})
.then(null, function(err) {
  //handle errors
});

2 个答案:

答案 0 :(得分:0)

async function findOrIncrease(title) {      
   let hashtag = await Hashtag.findOne({title});
   if(hashtag) {
     hashtag.userCounter++;
   } else {
     hashtag = new Hashtag({title, userCounter: 1});
   }
   await hashtag.save();
 }

可用作:

  (async function() {
    for(const title of tags)
      await findOrIncrease(title);
  })()

或者如果你想并行执行所有内容:

  tags.forEach(findOrIncrease);

您可以使用mongodbs索引加快速度。

答案 1 :(得分:0)

感谢@Jonas W的回复,还有我找到的另一个解决方案。我认为可能更好(因为它在性能中更清晰,更快)根据标签数组做出一些承诺并从这些承诺中解析标签文件(或者由于某些原因拒绝它们)。然后使用Promise.all()创建一个完整的承诺,提供mongoose文档(根据某些条件创建或更新)。它是这样的:

// some other chains
.then((xxxx) => {
        const hashtagsTitles = require('../../src/hashtags/hashtagParser').hashtags(req.newPost.caption);
        const Hashtag = require('../../src/database/models/Hashtag');

        let findOrIncrease = title =>
            new Promise((resolve, reject) => {
                Hashtag.findOne({
                        title
                    })
                    .then((hashtag) => {
                        if (!hashtag) {
                            new Hashtag({
                                    title,
                                    usageCount: 0
                                }).save()
                                .then(hashtag => resolve(hashtag._id))
                                .catch(err => reject(err));
                        } else {
                            hashtag.usageCount++;
                            hashtag.save()
                                .then(hashtag => resolve(hashtag._id))
                                .catch(err => reject(err));
                        }
                    })
                    .catch(err => reject(err));
            });

        let promiseArr = hashtagsTitles.map((hashtagTitle) =>
            findOrIncrease(hashtagTitle)
        );

        return Promise.all(promiseArr)
            .then(results => results)
            .catch(err => {
                throw err
            });
    })
    .then((hashtags) => {
        hashtags.forEach((hashtag) => req.newPost.hashtags.push(hashtag));
    })
    //there might be some other chains

此处有一个很好的指南: Mongoose - Create document if not exists, otherwise, update- return document in either case