mongodb / stitch-js-sdk

MongoDB Stitch JavaScript SDK
Apache License 2.0
113 stars 67 forks source link

serverless function, insertOne doesn't work. #262

Closed yumikohey closed 5 years ago

yumikohey commented 5 years ago

When I run this piece of code in the function editor, it successfully insert the entry. Then, I removed the entry, and call this function from React Native, it return Object {}. Why is that? Any setting is missing? I am able to login / sign up an user through the app.

    const newItem = {
        "userId": "5ca9783a6926e7b8bbf4798a",
        "firstName": "firstName",
        "lastName": "lastName"
    };
    const update = {
        "$set": {
            "firstName": firstName,
            "lastName": lastName
        }
    };
    const itemsCollection = mongodb.collection("userProfile");
    const query = { "userId": "5ca9783a6926e7b8bbf4798a" };
    return itemsCollection.updateOne(query, update)
        .then(result => {
            if (result.matchedCount === 0) {
                  return itemsCollection.insertOne(newItem)
                        .then(entry => {
                            return entry;
                        })
                        .catch(err => {
                            return err;
                        });
            } else {
              return result;
            }
        })
        .catch(error => {
            return error;
        });
tkaye407 commented 5 years ago

I assume you figured out what was wrong, but separately you may want to take a look at the upsert options for updateOne()

Stitch Docs: https://docs.mongodb.com/stitch/mongodb/update-documents-in-mongodb/#upsert-documents

MongoDB Docs: https://docs.mongodb.com/manual/reference/method/db.collection.update/