【问题标题】:insering a mongoose record if not found如果找不到则插入一条猫鼬记录
【发布时间】:2015-08-04 13:42:09
【问题描述】:

猫鼬模式如下所示:

var followSchema = new Schema({
  userId: {type: String, required: true},
  following : []
});

目标是使用 ID 字段查找用户,然后将项目添加到以下数组中。

以下方法无效:

var myRecord = FollowModel.findOneAndUpdate({userId: req.user.Id}, {upsert: true});
    myRecord.exec(function(err, result) {

        result.following.push('Test');
        res.status(200).send('New Item Added to Follow List');

    });

这是怎么做的?

【问题讨论】:

    标签: mongodb mongoose mongodb-query


    【解决方案1】:

    它确实有效,您只是忘记包含 { "new": true } 选项以及有效的更新声明:

    FollowModel.findOneAndUpdate(
       { "userId": req.user.Id}, 
       { "$setOnInsert": {
    
       }},
       { "upsert": true, "new": true },
       function(err,result) {
           if (err) throw err;
           console.log(result);
       }
    

    );

    在这种情况下,此处的空白$setOnInsert 将没有任何内容,否则您将在其中放入您想要“插入时”创建的内容。这将与语句“查询”部分中的任何字段一起应用。

    其他标准update operators 也可以应用,但通常是在您想要更新的“匹配”内容的情况下。

    但这里的{ "new": true } 让命令知道返回“修改或创建”文档,而不是“原始或不存在”文档,这是没有该选项的默认值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-10
      • 1970-01-01
      • 2022-01-01
      • 2020-08-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-15
      相关资源
      最近更新 更多