猫鼬批量执行创建(如果不存在),否则更新不包含时间戳

时间:2019-06-08 14:45:55

标签: node.js mongodb mongoose

编辑: 我知道<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>Title</title> <script src="https://www.gstatic.com/firebasejs/6.1.1/firebase-app.js"></script> <script src="https://www.gstatic.com/firebasejs/6.1.1/firebase-firestore.js"></script> </head> <body> <script> // Initialize Firebase var config = { apiKey: 'xxxxxx', authDomain: 'xxxxxx', databaseURL: 'xxxxxx', projectId: 'xxxxxx', appId: 'xxxxxx' }; firebase.initializeApp(config); var db = firebase.firestore(); let studentId = '1'; let unitNo = 'IT1'; let CG = 'F'; let PG = 'F'; let TG = 'F'; // Create a reference to the student doc. var gradeDocRef = db.collection('students').doc(studentId); console.log(gradeDocRef); db.runTransaction(function(transaction) { // This code may get re-run multiple times if there are conflicts. return transaction .get(gradeDocRef) .then(function(gradeDoc) { if (!gradeDoc.exists) { throw 'Document does not exist!'; } transaction.update( gradeDocRef, 'UnitGrades.' + unitNo, { CG: CG, PG: PG, TG: TG } ); }) .then(function() { console.log('Transaction successfully committed!'); }) .catch(function(error) { console.log('Transaction failed: ', error); console.log(studentId); }); }); </script> </body> </html> ,但似乎无法弄清楚该选项的传递方式...

setDefaultsOnInsert

当前正在构建通知系统。

这是我的代码当前的样子:

activity.notify.forEach( user_id => {
    query = { 'notification._id': activity._id, user_id, type: "replied to an idea you're subscribed to" }
    update = { $set: { notification: activity }, $addToSet: { user_details: user_data } }
    options = { setDefaultsOnInsert: true }

    bulk.find( query ).upsert().update( update, options )
} )

该代码的作用是通过一个名为let bulk = Notification.collection.initializeUnorderedBulkOp() activity.notify.forEach( user_id => { query = { 'notification._id': activity._id, user_id, type: "replied to an idea you're subscribed to" } update = { $set: { notification: activity }, $addToSet: { user_details: user_data } } bulk.find( query ).upsert().update( update ) } ) bulk.execute() .then( r => console.log( 'r', r ) ) .catch( err => console.log( 'bulk exec err ', err.writeErrors[ 0 ] ) ) 的包含notify的数组进行查找。

然后查看是否存在与上述user_ids类似的通知。如果是这样,请使用user_id将其更新为数组$addToSet


此方法的问题是它没有时间戳。在我的模型中,我有一行:user_details,但是由于我要添加一些文档,因此它们不会使用以下内容来进行文档的常规实例化:timestamps: true

是否有一种方法或方法可以自动包含这些内容或我必须创建一些辅助函数来生成new Notification()createdAt

这对我没用

0 个答案:

没有答案