NodeJS + Mongo:插入如果不存在,否则 – 更新

我在我的mongodb集合中有一个对象。 它的模式是:

{ "instruments": ["A", "B", "C"], "_id": { "$oid": "508510cd6461cc5f61000001" } } 

我的collections可能有这样的对象,但可能不会。 我需要检查是否存在带有关键“工具”的对象( 请注意,此时我不知道“工具”是什么值,它可能包含任何值或数组 ),如果存在,则执行更新;否则 – 插入一个新的值。 我怎样才能做到这一点?

 collection.find( { "instruments" : { $exists : true } }, function(err, object){ if (object) { //update } else { //insert } }); 

不起作用((

如果你想插入一个文件,如果没有find,你可以在update()函数中使用upsert选项:

 collection.update(selector, document, { upsert: true }); 

$exists例子:

假设你的藏书中有这6个文件

 > db.test.find() { "_id": ObjectId("5495aebff83774152e9ea6b2"), "a": 1 } { "_id": ObjectId("5495aec2f83774152e9ea6b3"), "a": [ ] } { "_id": ObjectId("5495aec7f83774152e9ea6b4"), "a": [ "b" ] } { "_id": ObjectId("5495aecdf83774152e9ea6b5"), "a": [ null ] } { "_id": ObjectId("5495aed5f83774152e9ea6b7"), "a": [ 0 ] } { "_id": ObjectId("5495af60f83774152e9ea6b9"), "b": 2 } 

如果要查找具有特定字段的文档,可以使用$ exists操作符( 节点文档 )使用find() )。 这也将返回包含一个空数组字段的文档。

 > db.test.find( { a: { $exists: true } } ) { "_id": ObjectId("5495aebff83774152e9ea6b2"), "a": 1 } { "_id": ObjectId("5495aec2f83774152e9ea6b3"), "a": [ ] } { "_id": ObjectId("5495aec7f83774152e9ea6b4"), "a": [ "b" ] } { "_id": ObjectId("5495aecdf83774152e9ea6b5"), "a": [ null ] } { "_id": ObjectId("5495aed5f83774152e9ea6b7"), "a": [ 0 ] }