如何处理mongoose中的一系列条目?

时间:2018-02-15 04:46:15

标签: javascript node.js mongodb express mongoose

我正在建立一个简单的博客网站,我有一个看起来像的帖子架构:

var postSchema = new mongoose.Schema({
    title: String,
    tags: String,
    category: {
        id: {
            type: mongoose.Schema.Types.ObjectId,
            ref: "Category",
        },
        name: String,
    },
    publishingDate: {
        type: Date,
        default: Date.now
    },
    content: String,
});

我的问题是:如何处理类别条目?

我将收到一系列类别,并按空格拆分以分隔每个类别,然后我需要一个能够覆盖每个类别的功能'类别并检查我的Category模型中是否存在(比较name值,如果没有,则创建它,然后最后传递所有类别对象,无论是构建还是找到创建帖子的函数

当我只有一个类别时,我能够通过编写一个检查传递的类别是否存在的函数来处理它,然后将新创建的(或可能找到的)类别传递给Post.create()

Post.create(newPost, function(err, newlyCreatedPost) {
    if (err) {
      // handle the error
    } else {
      // I wrote the 'findOneOrCreate' method as static in 'Category' model
      Category.findOneOrCreate({
        'name': categoryName
      }, function(err, usedCategory) {
        if (err) {
          //
        } else {
          newlyCreatedPost.category = usedCategory;
          newlyCreatedPost.save();
          console.log(newlyCreatedPost);
          res.redirect("/posts");
        }
      })
    }
  });

我对NodeJS,Express和MongoDB(mongoose)的整个事情还很陌生,所以欢迎所有的帮助或评论。

1 个答案:

答案 0 :(得分:0)

对类别使用批量upsert,它会找到更新或创建。欲了解更多信息,请阅读this

Post.create(newPost, function (err, newlyCreatedPost) {
    if (err) {
        // handle the error
    } else {
        var categories = "categorystring".split(' ');

        var bulk = Category.initializeUnorderedBulkOp();

        categories.forEach((categoryName) => {
            bulk.find({
                'name': categoryName
            }).upsert().update({
                $set:{'name': categoryName}
            });
        });
        bulk.execute(function (err, usedCategory) {
            if (err) {
                //
            } else {
                // do stuff
            }
        });
    }
});