简体   繁体   中英

Unable to Append Array Within MongoDB (mongoose) Document

I'm trying to append an empty array in a mongo database with a String that is created in the front-end (website ui), the relevant code snipets are as following:

mongoose Schema

    email: String,
    displayName: String,
    googleId: String,
    toIgnore: [{toIgnoreURL: String}]
})

document creation with passport & passport-google-oauth20

User.findOne({email: email.emails[0].value}).then((currentUser)=>{
            if(currentUser){
                // user does already exist
                console.log('welcome back!', currentUser)
                done(null, currentUser)
            }
            else{ // user doesn't exist yet
            new User({
                email: email.emails[0].value,
                displayName: email.displayName,
                googleId: email.id,
                toIgnore: []
            }).save().then((newUser)=>{
                console.log('new user created: ' + newUser)
                done(null, newUser)
            });
            }
        })

And lastly the attempt to append the toIgnore array property of the 'User' collection (of the currently logged in user)

User.update(
        {email: emailThisSession},
        {$push: {toIgnore: {toIgnoreURL: url}}})

In mongodb I see that the following document is successfully created

_id
:ObjectId(
IdOfDocumentInMongoDB)
toIgnore
:
Array
email
:
"myactualtestemail"
googleId
:
"longgoogleidonlynumbers"
__v
:
0

(Also as seen in attached image) document in mongodb ui

I don't seem to figure out how to actually populate the 'toIgnore' array. For instance, when console logging the following

var ignoreList = User.findOne({email:emailThisSession}).toIgnore;
console.log(ignoreList)

The output is undefined Note that console logging the url variable does indeed print the value I want to append to the array, I tried any format combination I could think of in the Schema builder and document creation, but I can't find figure the right way to get it done! Any help would be appreciated!

Update, using promises didn't work either

User.findOne({email:emailThisSession}).then((currentUser)=>{ //adding .exec() after findOne({query}) does not help as in User.findOne({email:emailThisSession}).exec().then(...)
            console.log(currentUser.toIgnore, url) //output is empty array and proper value for url variable, empty array meaning []
            currentUser.toIgnore.push(url)
        });

While adjusting the Schema as follows:

const userSchema = new Schema({
    email: String,
    displayName: String,
    googleId: String,
    toIgnore: []
})

Solution

I simply needed to change the update command to

User.updateOne(
            {email: emailThisSession},
            {$push: {toIgnore: {toIgnoreURL: url}}}).then((user)=>{
                console.log(user)
            })

Thanks @yaya!

Unable to add array element within a document with mongoose

  1. define your schema as:
const UserSchema = new mongoose.Schema({
  ...
  toIgnore: [{toIgnoreURL: String}]
})
  1. then you can create an object like this:
new User({
  ...,
  toIgnore: [] // <-- optional, you can remove it
})
  1. To check the value:
User.findOne({...}).then(user => {
  console.log(user.toIgnore)
});
  1. Your update statement should be:
User.update(
  {email: emailThisSession},
  {$push: {toIgnore: {toIgnoreURL: url}}}
).then(user => {
  console.log(user)
})

So in your case, this is undefined:

User.findOne({email:emailThisSession}).toIgnore

Since findOne is async. for getting the result, you can whether pass it a callback or you can use promises ( User.findOne({...}).then(user => console.log(user.toIgnore)) )

Update:

While adjusting the Schema as follows: new Schema({..., toIgnore: []})

Here is the problem with your update. you should change it back to: toIgnore: [{toIgnoreURL: String}]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM