首页 > 解决方案 > 如何不将多个数据保存到 mongodb 的集合中?

问题描述

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

标签: node.jsmongodb

解决方案


这是一个简单的实现,如果集合中已经存在文档,如何防止写入文档。

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);
    }
} );

推荐阅读