【问题标题】:Insert selective columns into collection using mongodb使用 mongodb 将选择性列插入集合
【发布时间】:2020-05-31 22:24:25
【问题描述】:

编写了一个触发器函数,当listingsAndReviews 集合中有插入时,它会将完整文档插入我的集合new_list

exports = function(changeEvent) {

    const fullDocument = changeEvent.fullDocument;

    const collection = context.services.get('Cluster0').db("sample_airbnb").collection("new_list");


    return collection.insertMany([fullDocument])
  .then(result => {
    console.log(`Successfully inserted ${result.insertedIds.length} items!`);
    return result;
  })
  .catch(err => console.error(`Failed to insert documents: ${err}`));

};

有没有办法在将数据插入 new_list 集合时只选择特定的必需列。 在这种情况下,我只需要插入 name 和 cart_id 并忽略其他。

我的样本收集列名称:

name     - string
cart_id   - objectid
number - string
address - string

【问题讨论】:

    标签: node.js mongodb triggers database-trigger mongodb-atlas


    【解决方案1】:

    您可以从fullDocument 中提取所需的属性,然后插入这个新对象:

    return collection.insertMany([{name: fullDocument.name, cart_id: fullDocument.cart_id }])
    

    Afaik 没有其他方法可以在 insert-methods 上“过滤”属性。 另请注意,您可以在此处使用insertOne 而不是insertMany,因为您只插入一个文档。

    【讨论】:

    • 这意味着fullDocument 已经未定义,即changeEvent 没有设置fullDocument
    • 是的,这就是我的意思 - changeEvent.fullDocument 未定义,因此 fullDocument 也是如此!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-04
    • 1970-01-01
    • 2013-03-29
    • 2020-09-15
    • 1970-01-01
    • 2020-11-08
    • 2020-08-24
    相关资源
    最近更新 更多