1

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();
Drew Tran
  • 21
  • 2
  • Are you trying to update the field that is not defined in the schema? I think you are trying to set user._id in profile attribute, but profile doesn't have the attribute defined. What are you getting from this console.log(array[i]) ? – notionquest Jul 12 '17 at 17:00
  • I'm trying to update the profile field and it is defined in the Schema. The update call looks for the _id and set the profile field to array[i]. When i console.log array[i], I get the correct profile object that I want to replace the old one with. – Drew Tran Jul 12 '17 at 17:11

0 Answers0