I'm new to the async/await world and trying to experiment a bit with Mongoose + MongoDB + Node.JS I have this piece of code
exports.updateBrandPreferences = async (req,res) => {
var userID = req.body.playerID;
var newBrands = req.body.brandList;
console.log("Ricevuto la seguente lista: " + newBrands);
async.each(newBrands, function(brand,error) {
Brand.findOneAndUpdate({'name': brand},{$addToSet: {peopleInterested: userID}}, {new:true}).exec().then((results) => {
console.log(results);
User.findOneAndUpdate({_id: userId},{$addToSet: {interestedBrands: results._id}}, {new:true}).exec().then((risultato)=> {
console.log(risultato);
return risultato;
}).catch((err) => {
return "error";
});
return results;
}).catch((err) => {
return "error";
});
});
return res.status(200).json({"message": "OK"});
};
Taking some elements from the request, my objective is to associate the specified user with a list of some brands of interest. While the first query works (so Brands do now have new users inside them to symbolize their interest), this doesn't work for users as the second query doesn't get executed.
What am I missing? Schemas are the following:
Brand :
var BrandSchema = new Schema({
name: {type: String, required: true, unique: true},
peopleInterested: Array,
}, {
collection: 'brands',
retainKeyOrder: true,
timestamps: true,
}).plugin(mongoosePaginate);
User:
var UserSchema = new Schema({
isAdmin: {type: Boolean, default: false},
name: String,
surname: String,
email: { type: String, lowercase: true, required: true, trim: true, unique: true, dropDubs: true },
password: { type: String, required: true },
salt: { type: String },
verified: { type: Boolean, default: false },
bio: {
type: { type: String, enum: [0,1] }, // 0='Squadra', 1='Giocatore'
birthday: String,
height: Number,
number: Number,
role: { type: String, enum: [0,1,2,3] }, // 0='Playmaker', 1='Ala', 2='Guardia', 3='Centro'
team: String,
city: String,
fiscalCode: {type: String, maxlength:16}
},
newsletter: {type: Boolean, default: false},
lastCheckin: {type: mongoose.Schema.Types.ObjectId, ref: 'Checkin'},
follows: [{type: mongoose.Schema.Types.ObjectId, ref: 'Structure'}],
interestedBrands: Array,
score: { type: Number, default: 0 },
profilePicture: String,
lastLogin: {type: Date},
facebook: {
id: String,
accessToken: String,
profileImage : String
}
}, {
collection: 'users',
retainKeyOrder: true,
timestamps: true,
}).plugin(mongoosePaginate);