如何不将一个以上的数据保存到mongodb中的集合中?

时间:2019-10-11 07:36:12

标签: node.js mongodb

如果该集合中已经存在数据,我不想保存其他数据

1 个答案:

答案 0 :(得分:0)

这是一个简单的实现,用于在Collection中已经存在文档的情况下如何防止编写文档。

Collection.find( {}, (err, docs) => { // By not giving any arguments inside "{}", you tell MongoDB to return all the documents.
    if(docs) {  // If there are any documents already present in the Collection, this will become true and nothing will happen.
        return;
    } else {  // If there's no document already present in the Collection, new document will be added.
        Collection.save(doc);
    }
} );