RethinkDB 替换文档但不具体 属性

RethinkDB replace document but not specific property

我想在一个查询中应用文档替换,但我想保留旧文档中的特定 属性 (createdAt)。

旧文档:

{id: "xxx" title: "my title", description: "my desc", createdAt: "1507844981006"}

新建文件

{id: "xxx" title: "my title2", description: "my desc2", createdAt: "1507844981006"}

约束是:

我的初始查询如下所示

const data = {id: "xx"....};

r.table('mytable')
 .get(id)
 .replace((row) => {

    return r.expr(data).merge(row.pluck('createdAt'))

 }
 .run()

有人建议执行此操作吗?

提前致谢

i want to perform a replacement and not an update to apply a document insertion, in case the document do not exists.

你要找的是"upsert"(或者"replsert",如果我们在RethinkDB中可以这样命名的话),据我所知,RethinkDB中没有这样的操作. .replace() 至少需要找到一个文档,因此无法插入。然而,它可以很容易地实现,也可以用 ReQL 香料来调味。

下面的例子可以直接在Data Explorer中测试:

const OLD_DOCUMENT = { id: 'xxx', title: 'my title', description: 'my desc', createdAt: '1507844981006' };
const NEW_DOCUMENT = { id: 'xxx', title: 'my title2', description: 'my desc2' };

r.db('TEST')
  .table('TEST')
  .delete();

// Comment out the following query to test the .insert() scenario,
// or uncomment it to test the .replace() scenario
r.db('TEST')
  .table('TEST')
  .insert(OLD_DOCUMENT);

r.db('TEST')
  .table('TEST')
  .replace((doc) => r.expr(NEW_DOCUMENT).merge(doc.pluck('createdAt')))
  .do(replaceData => r.branch(
    // Did the .replace() operation succeed with a real replacement?
    replaceData.getField('replaced').gt(0),
    // Then just return the replace result
    replaceData,
    // Otherwise, perform an insert
    r.db('TEST')
      .table('TEST')
      .insert(
        // Bonus (not just .insert(NEW_DOCUMENT))
        r.branch(
          // Does the document have the createdAt property set?
          r.expr(NEW_DOCUMENT).hasFields('createdAt'),
          // If yes, then no transformation is required
          NEW_DOCUMENT,
          // Else add the timestamp in your format
          r.expr(NEW_DOCUMENT).merge({ createdAt: r.now().toEpochTime().mul(1000).coerceTo('string') })
        )
      )
));

r.db('TEST')
  .table('TEST');

.insert() 情景结果

{
  "createdAt": "1507890036302", // this property value will grow in time
  "description": "my desc2",
  "id": "xxx",
  "title": "my title2"
}

.replace() 场景结果

{
  "createdAt": "1507844981006", // this value never changes in your test
  "description": "my desc2",
  "id": "xxx",
  "title": "my title2"
}

关于风格和偏好,可以重复使用以下表达式:

  • const TABLE_EXPR = r.db('TEST').table('TEST');
  • const NEW_DOCUMENT_EXPR = r.expr(NEW_DOCUMENT);