0

Just got into working with MongoDB to create a back-end for my express/node.js website. The premise of my problem is that i'm trying to use a nested array as a "posts" section for a social network (different for every user). As such i have formatted the schema as shown below

var Posts = mongoose.Schema({
    "title" : String,
    "Body" : String,
    "Likes" : Number
});

var userSchema = mongoose.Schema(
    {
        "email": String,
        "password": String,
        "first_name": String,
        "last_name": String,
        "posts" : Posts
    }
);

My main goal is to be able to say add a new post with the press of a button and the code i've been attempting to use to accomplish that is shown below

var User = require("../models/user.js")

User.findOneAndUpdate(
    {email : req.session.user.email}, 
    {"$push" : { "title" : "test title", "body" : "testbody", "likes" : 5}}
);

But the execution of that codeblock seems to do nothing when i check the backend after the fact. I've tried a variety of other methods to no avail. Some help would be much appriciated!

Ivan Beldad
  • 2,285
  • 2
  • 21
  • 33
haseo98
  • 1
  • 1
  • Because your schema does not know it's an "array". Use `"posts": [Posts]` instead. Then follow the the existing answers you are linked to. – Neil Lunn Apr 30 '18 at 11:49
  • `{ "$push" : { "posts": { "title" : "test title", "body" : "testbody", "likes" : 5 } } }` – Neil Lunn Apr 30 '18 at 11:50

0 Answers0