嗨,我是节点js mongodb的初学者。我想在mongodb中插入数据。首先我检查用户存在于用户集合然后数据插入和完成过程后然后回调。请提出建议
exports.contactSync = function contactSync(data, userId, callback) {
var Promise = require('promise');
MongoClient.connect(Mongo_url, function (err, db) {
assert.equal(null, err);
db.collection('contacts').deleteMany({user_id: userId});
var bulk = db.collection('contacts').initializeOrderedBulkOp(),
counter = 0;
data.forEach(function (doc) {
let promises = [];
db.collection('users').findOne({email: doc.trim()}, {user_id: 1}).then(function (userData) {
promises.push(new Promise(resolve => {
bulk.insert({user_id: userId, contact_id: userData.user_id});
}));
});
counter++;
if (data.length == counter) {
return Promise.all(promises);
bulk.execute(function (err, r) {
// do something with the result
console.log("succes");
});
}
});
if (counter > 0) {
bulk.execute(function (err, result) {
console.log("succes");
callback({'error': 0, 'message': 'Successfull synchronization', 'data': null, 'status': 200});
// do something with the result here
});
}
}
答案 0 :(得分:0)
无法访问buld.execute
if (data.length == counter) {
return Promise.all(promises);
bulk.execute(function (err, r) {
// do something with the result
console.log("succes");
});
}
答案 1 :(得分:0)
您可以使用inserMany()方法将批量数据插入MongoDB。
承诺的例子:
Collection1.insertMany(myData)
.then(function(docs) {
// do something with docs
})
.catch(function(err) {
// error handling here
});
答案 2 :(得分:0)
我给出了样本,您只想按照承诺
插入批量数据的方式//var Q = require('q');
//insertData = [{name: "abcd"},{name: "efgh"},{name: "xyz"}]
router.post('/', function(req, res) {
var spec = {};
var deleteData= req.deleteData;
Q(spec).then(function(spec) {
//add your delete records logic
var deferred = Q.defer();
var collection = collection_name;
//here assign your db with collection name
collection.deleteMany(deleteData, function(err, user) {
if (!err && user) {
spec.delete= user;
deferred.resolve(spec);
} else {
spec.message = "Please retry";
deferred.reject(spec);
}
});
return deferred.promise;
}).then(function(spec) {
var deferred = Q.defer();
var collection = collection_name;
//here assign your db with collection name
collection.insertMany(insertData, function(err, user) {
if (!err && user) {
spec.user = user;
deferred.resolve(spec);
} else {
spec.message = "Please retry";
deferred.reject(spec);
}
});
return deferred.promise;
}).then(function(spec) {
res.json(spec);
//send your response
}).fail(function(spec) {
res.json(spec);
//send your error response
});
}