如果条件在mongodb中添加元素到数组

时间:2019-12-13 20:38:23

标签: mongodb conditional-statements push

仅当此元素通过特定条件时,我才尝试执行查询以将元素添加到mongodb集合中文档的数组中。

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

现在,将这样的对象:{ user: 'user1', answer: 'hello world' }传递到我的端点,我希望数据库检查回答用户是否已经回答,如果已经回答,则返回错误或类似MySQL的内容( UpdatedRows:n),相反,如果用户尚未回答,只需将其回答推入答案数组的底部即可。

预先感谢

1 个答案:

答案 0 :(得分:1)

请尝试以下示例::

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

    }
});

if子句中,我们要检查res.result.nModified是否为正整数,以便说已插入记录,否则它将是伪造的值,即; 0,然后存在重复记录。

参考: $pushupdateOne