Nimrod
Nimrod

Reputation: 389

Doubts on Mongodb query

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.

Upvotes: 0

Views: 43

Answers (1)

tunchunairarko
tunchunairarko

Reputation: 101

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

Upvotes: 1

Related Questions