我正在使用以下函数来注册用户进行“出价”。用户有一个 bids 数组,它将把 bids 放入数组中,并将其保存为用户模型的一部分。我正在使用以下函数来完成此操作:
// Register client for bid
module.exports.register = function(info, callback) {
client_username = info['client_username'];
bid_id = info['bid_id'];
bid_title = info['bid_title'];
var query = {username: client_username};
Client.findOneAndUpdate(
query,
{$addToSet: {"bids": {bid_id: bid_id, bid_title: bid_title}}},
{safe: true, upsert: true},
callback
);
}
问题是,我没有检查客户的出价数组中是否已经有此出价。我对 mongoDb 和 js 不太了解,无法在使用 $addToSet 并将新的出价添加到数组之前检查出价数组。不过我认为这就是 $addToSet 应该做的事情。
有谁知道如何迭代用户的出价数组来检查我插入数组的出价是否已存在于数组中?请参阅下面的完整出价模型和客户模型。
var mongoose = require('mongoose');
// client Schema
var clientSchema = mongoose.Schema({
first_name: {
type: String
},
last_name: {
type: String
},
address: [{
street_address:{type: String},
city:{type: String},
state:{type: String},
zip:{type: String}
}],
username: {
type: String
},
email: {
type: String
},
bids:[{
bid_id:{type: [mongoose.Schema.Types.ObjectId]},
bid_title: {type:String}
}]
});
var Client = module.exports = mongoose.model('Client', clientSchema);
module.exports.getClientByUsername = function(username, callback){
var query = {username: username};
Client.findOne(query, callback);
}
// Register client for bid
module.exports.register = function(info, callback) {
client_username = info['client_username'];
bid_id = info['bid_id'];
bid_title = info['bid_title'];
var query = {username: client_username};
Client.findOneAndUpdate(
query,
{$addToSet: {"bids": {bid_id: bid_id, bid_title: bid_title}}},
{safe: true, upsert: true},
callback
);
}
最佳答案
我在我的 MongoDB 实例上进行了本地测试。使用 FindAndModify() 时,$AddtoSet 仅在数组中不存在时添加新出价。如果它存在,则不会执行任何操作。这是我使用的查询:
db.collection.findAndModify({
query: {
"username": "ag102"
},
update: {
$addToSet: {
"bids": {
"bid_id": 6,
"bid_title": "ebay6"
}
}
},
upsert: true
});
关于javascript - Mongodb,在插入新值之前检查对象/模型的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34419795/