1

I'm trying to do a query to add an element to an array in a document in a mongodb collection, only if this element passes a certain condition.

{
    _id: ObjectId,
    author: String,
    answers: [
        { user: 'user1', answer: 'hello1' },
        { user: 'user2', answer: 'hello2' },
        { user: 'user3', answer: 'hello3' },
    ]
}

Now, passing an object like this: { user: 'user1', answer: 'hello world' } to my endpoint, I would like the database to check if the user who answered had already answered and if he already had, return an error or something like in MySQL (updatedRows: n) and instead, if the user hadn't already answered, simply push his answer at the bottom of the array of answers

Thanks in advance

1
  • Is it OK for the match on user and answer to apply to more than one author? Commented Dec 13, 2019 at 22:24

1 Answer 1

1

Please try this sample ::

const MongoClient = require('mongodb').MongoClient;

// Connection URL
const url = 'your DB url';

// Create a new MongoClient - initializing client
const client = new MongoClient(url);

// Use connect method to connect to the Server    
client.connect(async function (err, db) {
    if (err) console.log('Err in connection ::', err)
    console.log("Connected successfully to server");
    try {
        let database = db.db();
        let conn = database.collection('yourCollectionName')

        /** This is what exactly needed, just pass 'user1' taken from input object
            & pass it in filter query, So if the user already exists in array then the record won't be added,
              otherwise will be pushed to array. */

        let res = await conn.updateOne({ "author": "me",'answers.user': {$ne : 'user1'} }, {
            $push: {
                answers: {
                    "user": "user1",
                    "answer": "hello world"
                }
            }
        })

        if (res.result && res.result.nModified) {
            console.log('Added new record')
        } else {
            console.log('Record already exists')
        }
        client.close();
    } catch (error) {
        console.log('error ::', error)
        client.close();

    }
});

In if clause we're checking res.result.nModified to be a positive integer in order to say record inserted, otherwise it will be falsy value i.e; 0 then duplicate record exists.

Ref : $push, updateOne

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.