N
N
Nikita Shchypylov2018-07-14 12:51:06
MongoDB
Nikita Shchypylov, 2018-07-14 12:51:06

Why is the whole "scheme" littered when an element is added to a user?

Hello!
The functionality adds a new post to a specific user's array. Here is the code:

Router.route("/newpost").post(function(req, res) {
  UserSchema.findById(req.body.user).then((user) => {
    const id = function() {
      return (
        "_" +
        Math.random()
          .toString(36)
          .substr(2, 9)
      );
    };
    req.body.data.key = id();
    user.posts.unshift(req.body.data);
    user.save();
    console.log("--- user", user);
    res.send(user);
  });
});

Schema :
const mongoose = require("mongoose")
const Schema = mongoose.Schema

const UserSchema = new Schema({
    name : {
        type: String
    },
    login : {
        type: String
    },
    posts : {
        type : Array
    },
    email : {
        type: String
    },
    password : {
        type: String
    },
})

module.exports = mongoose.model("UserSchema", UserSchema, "users")

Adds successfully, but also creates an empty object in the "users" directory:
5b49c76a7e08e551650741.png
What causes this behavior? I want it to only add to the con th user's array.
Thank you!

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question