我正在 node.js、mongodb 和 express 中处理一个必须处理事务的项目。我可以硬编码要放入 mongodb 的变量,但如果没有填写所有字段(并非所有字段都是必需的),那么我只是将空数据放入数据库中。
此代码有效:
var d = new Date();
var n = d.toJSON();
var date = n;
var address = req.body.property_address;
var client_name = req.body.client_name;
var sales_price = req.body.sales_price;
var commission_percent = req.body.commission_percent;
var referral = req.body.referral;
var donation = req.body.donation;
var client_source = req.body.client_source;
var client_type = req.body.client_type;
var notes = req.body.notes;
Transaction.findOne({ name: { $regex: new RegExp(date, "i") } },
function(err, doc){
if(!err && !doc) {
console.log("there is no error, and this does not already exist");
var newTransaction = new Transaction();
newTransaction.date = date;
newTransaction.address = address;
newTransaction.client_name = client_name;
newTransaction.sales_price = sales_price;
newTransaction.commission_percent = commission_percent;
newTransaction.referral = referral;
newTransaction.donation = donation;
newTransaction.client_source = client_source;
newTransaction.client_type = client_type;
newTransaction.notes = notes;
newTransaction.save(function(err) {
if(!err){
console.log("successfully saved");
res.json(200, {message: newTransaction.date});
} else {
res.json(500, {message: "Could not create transaction. Error: " + err})
}
});
}
});
但是将一个不存在的值放入 mongodb 有什么意义呢?这不是应该很棒的事情之一吗?我的想法是,它消除了我将来可能做的可能的查询。
有可能做更多这样的事情吗?
Transaction.findOne({ name: { $regex: new RegExp(date, 'i' ) } },
function(err, doc){
if(!err && !doc){
var newTransaction = new Transaction();
for(var key in req.body){
newTransaction.key = req.body[key];
}
}
}
});
更新
这是我最终使用的代码。
Transaction.findOne({ name: { $regex: new RegExp(date, "i") } },
function(err, doc){
if(!err && !doc){
var newTransaction = new Transaction();
for(var key in req.body){
if(req.body[key] != ''){
newTransaction[key] = req.body[key];
}
}
}
}
});