0

I was designing a classifieds web app with the MERN stack. The MongoSchema is as shown below

const UserSchema = new Schema({
    name: {
        type: String,
        required: true
    },
    email: {
        type: String,
        required: true
    },
    password: {
        type: String,
        required: true
    },
    books: [{
        title: { type: String },
        author: { type: String },
        desc: { type: String },
        price: { type: String },
        image: { data: Buffer, contentType: String }
    }],
    date: {
        type: Date,
        default: Date.now
    }
});

So all the other info except the books[] will be available after the initial sign-up, but what I want to do is to update the books array every time the user wishes to post a book for selling.

I'm planning to find the user by id, but I'm not quite sure how to add/append the info to the books array.

1 Answer 1

1

There are some answers to your question already in Stackoverflow. For example: Using Mongoose / MongoDB $addToSet functionality on array of objects

You can do something like this:

UserModel.js

const mongoose = require("mongoose");

const UserSchema = new Schema({
    name: {
        type: String,
        required: true
    },
    email: {
        type: String,
        required: true
    },
    password: {
        type: String,
        required: true
    },
    books: [{
        title: { type: String },
        author: { type: String },
        desc: { type: String },
        price: { type: String },
        image: { data: Buffer, contentType: String }
    }],
    date: {
        type: Date,
        default: Date.now
    }
});
module.exports = User = mongoose.model("user", userSchema);

After that, in your router file you can try something like this for the books array:

const res = await User.updateOne({ email: '[email protected]' }, {'$addToSet':{
'books':{
        title: "Gintama: The Final",
        author: "Sorachi",
        desc: "Final Arc",
        price: "44.99",
        image: "src"
    }}); //addToSet if you don't want any duplicates in your array.

OR

const res = await User.updateOne({ email: '[email protected]' }, {'$push':{
    'books':{
            title: "Gintama: The Final",
            author: "Sorachi",
            desc: "Final Arc",
            price: "44.99",
            image: "src"
        }}); //push if duplicates are okay in your array
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, so addToSet was what I was missing.
Yes. In some cases where you might work with quantitative numerical array, you will need push operator.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.