【问题标题】:Mongoose get collection data if present the update otherwise insertMongoose 如果存在更新则获取集合数据,否则插入
【发布时间】:2016-09-16 11:08:01
【问题描述】:

我是 mongodb 和 ExpressJS 的新手。这可能是一个简单的问题,但我没有成功。

var BookCounter = new Schema({
    counter: {type: Number,},
    book: {type: String, min: 18}
});

这是我的架构,以下是我的问题:

我想检查 xyz 书是否存在

如果有书

那么我必须将图书计数器更新一。

否则

我必须插入新书。

你能帮帮我吗..

提前致谢:)

【问题讨论】:

    标签: node.js mongodb express mongoose


    【解决方案1】:

    您需要更新操作 findOneAndUpdate(),如果文档不存在,则使用选项 upsertnew 选项如果设置为 true,则返回新创建/修改的文档而不是原始文档,以及 $set$inc 字段更新运算符。

    以下示例演示了这一点:

    var query = { "book": "xyz" },
        update = { "$inc": { "counter": 1 } },
        options = { "upsert": true, "new": true };
    
    // Find the document
    Book.findOneAndUpdate(query, update, options, function(err, result) {
        if (err) handleError(err);    
        else {
            // do something with the document
            console.log(JSON.stringify(result, null, 4));
        }
    });
    

    【讨论】:

      猜你喜欢
      • 2015-12-17
      • 1970-01-01
      • 2014-05-05
      • 2014-10-23
      • 2013-04-19
      • 2023-03-17
      • 1970-01-01
      • 2010-12-10
      • 2015-07-04
      相关资源
      最近更新 更多