简体   繁体   English

MongoDB Mongoose使用数组保存或更新

[英]MongoDB Mongoose save or update with array

When a user saves a question, the question can contain an array of "tags". 当用户保存问题时,该问题可以包含“标签”数组。 I want to take that array of tags and check to see if they exist in the tag collection. 我想采用该标签数组,并检查它们是否存在于标签集合中。 If the tags exist, update the count, if not, add it to the collection. 如果标签存在,请更新计数,否则,将其添加到集合中。 I have code written to do this but it seems very verbose. 我已经编写了代码来执行此操作,但是它看起来很冗长。 Is there a better/easier/more concise way to do this with mongo/mongoose? 使用mongo / mongoose是否有更好/更简便/更简洁的方法? The functionality is kind of similar to how stack overflow works with it's tagging. 该功能有点类似于堆栈溢出对其标记的工作方式。

apiRouter.post('/', function(req, res) {
    var question = new Questions();

    question.text = req.body.text;
    question.answers = req.body.answers;
    question.tech = req.body.tech;
    question.tags = req.body.tags;
    question.level = req.body.level;
    question.createdAt = req.body.createdAt;

    question.save(function(err, questions) {
        if(err) res.send(err);
        res.json({message: "Question was created."});
    });

    for each(tag in req.body.tags) {
        QuestionTags.find({ 'tag': { $regex: new RegExp(tag, "i") } }, function(err, tags) {
            if(err) res.send(err);
            if(tags.length === 0) {
                var tagObj = new QuestionTags();
                tagObj = {
                    tag: tag,
                    count: 0
                }
                tagObj.save(function(err, questions) {
                    if(err) res.send(err);
                    res.json({message: "Tag created"});
                });
            } else {
                var tagObj = new QuestionTags();
                tagObj = tags;

                tagObj.count++;

                tagObj.save(function(err, questions) {
                    if(err) res.send(err);
                    res.json({message: "Tag updated"});
                })
            }
        })
    }
});

You can use the MongoDB $in operator expression when using find() with stream() from the Mongoose API. 当从Mongoose API将find()stream()结合使用时,可以使用MongoDB $ in运算符表达式。 find() returns a Query object which can then be used to create a QueryStream (which implements the Node.js ReadableStream interface). find()返回一个Query对象,然后可以使用该对象创建QueryStream (实现Node.js ReadableStream接口)。 You can then use .on to handle each stream event. 然后,您可以使用.on处理每个流事件。

Note that you cannot use $regex operator expression inside of an $in expression, so you will have to take care of that before passing the array into find() . 请注意,您不能在$in表达式内使用$regex运算符表达式,因此在将数组传递给find()之前,您必须注意这一点。

apiRouter.post('/', function(req, res) {
    var question = new Questions();

    question.text = req.body.text;
    question.answers = req.body.answers;
    question.tech = req.body.tech;
    question.tags = req.body.tags;
    question.level = req.body.level;
    question.createdAt = req.body.createdAt;

    question.save(function(err, questions) {
        if(err) res.send(err);
        res.json({message: "Question was created."});
    });

    var tagsRegExp = [];

    req.body.tags.forEach(function(tag) {
        tagsRegExp.push(new RegExp(tag, "i");
    }

    QuestionTags.find({ 'tag': { $in : tagsRegExp }}).stream()
        .on('error', function(err) {
            res.send(err);
        }).on('data', function(tag) {
            if(tag.length === 0) {
                var tagObj = new QuestionTags();
                tagObj = {
                    tag: tag,
                    count: 0
                }
                tagObj.save(function(err, questions) {
                    if(err) res.send(err);
                    res.json({message: "Tag created"});
                });
            } else {
                var tagObj = new QuestionTags();
                tagObj = tag;

                tagObj.count++;

                tagObj.save(function(err, questions) {
                    if(err) res.send(err);
                    res.json({message: "Tag updated"});
                });
            }
        });
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM