Search code examples
javascriptmongodbsavemongoose-schemamongoose-populate

Can't save changed Object back to MongoDB Database


what I am trying to do is find an object with the corresponding object Id, push a new Id into an array of that object (which does work)

and then save the object back into the MongoDB database. But the group.save() just returnes an error.

enter image description here

My Code:

    addPlacemarkToGroup: {
        handler: async function (request, h) {
            const loggedInUser = request.auth.credentials;
            const user = await db.userStore.getUserById(loggedInUser._id);

            const placemark = await db.placemarkStore.getPlacemarkById(request.payload.placemarkId);
            const group = await db.groupStore.getGroupById(request.payload.groupId);

            console.log(group);

            group.arrayOfPlacemarkIds.push(placemark._id);

            await group.save();

            console.log(group);

            return h.redirect("/dashboard");
        },
    },

My Schema:

import Mongoose from "mongoose";
import { User } from "./user.js";
import { Placemark } from "./placemark.js";

const { Schema } = Mongoose;

const groupSchema = new Schema({
    title: String,
    userId: {
        type: Schema.Types.ObjectId,
        ref: "User",
    },
    arrayOfPlacemarkIds: [{type: [Schema.Types.ObjectId], ref:"Placemark"}]
});

export const Group = Mongoose.model("Group", groupSchema);


Solution

  • You didn't share user and placemark so I added a dummy collection for them. One problem i saw was the type of arrayOfPlacemarkIds, it was defined as an array of arrays. Other thing i dont know what is your groupStore so I just used a findOne. This is a one-file working example, just place your connection string, run, copy the body printed in the console and hit a post request to http://localhost:3000/add

    const express = require("express");
    var cors = require('cors')
    
    const app = express();
    
    app.use(express.json());
    app.use(cors());
    
    const mongoose = require('mongoose');
    mongoose.set('strictQuery', true);
    
    const { Schema } = mongoose;
    
    const userSchema = new Schema({
        name: String
    });
    
    const placemarkSchema = new Schema({
        name: String
    });
    
    const groupSchema = new Schema({
        title: String,
        userId: {
            type: Schema.Types.ObjectId,
            ref: "User",
        },
        arrayOfPlacemarkIds: [{ type: Schema.Types.ObjectId, ref: "Placemark" }] // 🟥 was as array: [Schema.Types.ObjectId] 
    });
    
    const Group = mongoose.model("Group", groupSchema);
    const User = mongoose.model("User", userSchema);
    const Placemark = mongoose.model("Placemark", placemarkSchema);
    
    (async function ConectToDBAndPrepareData() {
        await mongoose.connect("mongodb://@0.0.0.0:50000", { dbName: "" });
    
        await User.deleteMany();
        await Group.deleteMany();
        await Placemark.deleteMany();
    
        const user = await User.create({ name: "User" });
        const placemark1 = await Placemark.create({ name: "Placemark 1" });
        const placemark2 = await Placemark.create({ name: "Placemark 2" });
        const group = await Group.create({ titke: "Group", userId: user._id, arrayOfPlacemarkIds: placemark1 });
    
        const body = {
            userId: user._id.toString(),
            placemarkId: placemark2._id.toString(),
            groupId: group._id.toString()
        }
    
        console.log(JSON.stringify(body, null, 2)); //🟥 payload to send a POST request to http://localhost:3000/add
    })();
    
    
    app.post("/add", async function (request, h) {
        const placemark = await Placemark.findOne({ _id: request.body.placemarkId });
    
        if (!placemark) {
            return h.json("placemark not found");
        }
    
        const group = await Group.findOne({ _id: request.body.groupId });
    
        if (!group) {
            return h.json("group not found");
        }
    
        if (group.arrayOfPlacemarkIds.some(id => id.equals(placemark._id))) {
            return h.json("placemark already added");
        }
    
        group.arrayOfPlacemarkIds.push(placemark._id);
    
        await group.save();
    
        return h.json("OK!");
    })
    
    const PORT = 3000;
    app.listen(PORT, function (err) {
        if (err) console.log(err);
        console.log("Server listening on PORT", PORT);
    });