This is my user model:
const userSchema = new Schema({
name: String,
email: {type: String, unique: true},
password: String,
verified: Boolean,
profile: {
avatar: String,
name: String,
lai: String,
actions: Number,
points: Number
}
}
I'm trying to update the profile property for multiple users, and as you can see each profile is unique to the user.
const User = require('../models/user');
const mongoose = require('mongoose');
function updateUsers(){
let array = {};
User.find({}, function(err, users) {
users.forEach(function(user) {
let updated = {
"avatar" :
"",
"name" : user.name,
"lai" : "",
"actions" : 0,
"points" : 0
};
array[user._id] = updated;
});
userUpdate(array);
});
}
So I was able to save the _ids and new profile objects to an array.
function userUpdate(array){
console.log(array);
for (i in array){
console.log("id is: " + i);
console.log(array[i]);
User.update({_id: i}, {$set: {profile: array[i]}});
console.log("after call");
}
}
But the above update call won't update the users in the database. It's basically doing nothing and not throwing any error. I tried casting the id to objectId, changing the $set call to something else too or change update to findByIdAndUpdate but nothing has worked. What am I doing wrong here?
EDIT: I fixed the problem. It seems like that update call needs to be used with promises. I added the statement below and it's working properly.Whoosh!
User.findByIdAndUpdate({_id: i}, {$set: {profile: array[i]}})
.then(() => User.findById({_id: i}))
.catch();