0

Good evening,

I have my model

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const widgetSchema = new Schema({
    city: {
        type: String
    }
})

const userSchema = new Schema({
    name: {
        type: String,
    },
    password: {
        type: String
    },
    widgets: [widgetSchema]
})


const User = mongoose.model('user', userSchema);

module.exports = User;

And my question is how can I add elements to the widget array? Should I use an update or what? I think, firstly I need to find user document:

app.post('/addwidget', async (req, res) => {
    const { city } = req.body;
    try {
        const user = await User.findOne({"name": "1"});
    }
    catch(err){
        console.log(err)
    }
})

and thank what? Is there method like push or something like that?

3 Answers 3

1

Try this one :

  try {
    const user = await Research.findOneAndUpdate({ name: '1' }, { $push: { widgets: { city: 'viking' }} })
    if (user) return user;
    else return false;
  } catch (error) {
     console.log(error);
  }
Sign up to request clarification or add additional context in comments.

Comments

1

you can use $push or $addToSet to add new item to the widgets array :

app.post('/addwidget', async (req, res) => {
    const { city } = req.body; // 
    try {
        const user = await User.findOneAndUpdate({"name": "1"} , { $push: { widgets: city }});
    }
    catch(err){
        console.log(err)
    }
})

or :

app.post('/addwidget', async (req, res) => {
    const { city } = req.body;
    try {
        const user = await User.findOneAndUpdate({"name": "1"} , { $addToSet : {widgets: city }});
    }
    catch(err){
        console.log(err)
    }
})

Comments

0

From the doc: Adding Subdocs to Arrays, you can use MongooseArray.prototype.push()

E.g.

app.post('/addwidget', async (req, res) => {
  const { city } = req.body;
  try {
    const user = await User.findOne({ name: '1' });
    user.widgets.push({ city: 'viking' });
    await user.save();
  } catch (err) {
    console.log(err);
  }
});

Comments

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.