ayotycoon
ayotycoon

Reputation: 199

push items to an array in a object using Mongoose

I want to update the posts array in the data object. It dosent work here is my schema:

const mongoose = require('mongoose');
const Post = require('./post');
const Review = require('./comment')

    const User = mongoose.Schema({
        _id: mongoose.Schema.Types.ObjectId,

        username: {
            type: String,
            required: true
        }

        // necessary details needed for the user to initially working with
        data: {

            posts: [
                Post
            ],
            following: [String]
            }
        }

    });

I have already tried:

User.update({_id: user}, {data:{$push: {posts: post
  }}}).then(data=>{
    console.log(data);
  })

but it dosent work. Thank you.

Upvotes: 1

Views: 4150

Answers (1)

Harshal Yeole
Harshal Yeole

Reputation: 4983

Try this code:

User.update(
    { "_id": user },
    {
        "$push":
            {
                "data.posts": post
            }
    }
).then(data => {
    console.log(data);
})

Read more about $push here.

Hope this solves your query!

Upvotes: 2

Related Questions