Push items into mongo array via mongoose

前端 未结 8 1379
小鲜肉
小鲜肉 2020-11-22 03:22

I\'ve scoured SO a good bit looking for the answer but I\'m sure that I\'m lost for the right words to describe what I\'m after.

Basically I have a mongodb collection

相关标签:
8条回答
  • 2020-11-22 04:04

    The $push operator appends a specified value to an array.

    { $push: { <field1>: <value1>, ... } }
    

    $push adds the array field with the value as its element.

    Above answer fulfils all the requirements, but I got it working by doing the following

    var objFriends = { fname:"fname",lname:"lname",surname:"surname" };
    Friend.findOneAndUpdate(
       { _id: req.body.id }, 
       { $push: { friends: objFriends  } },
      function (error, success) {
            if (error) {
                console.log(error);
            } else {
                console.log(success);
            }
        });
    )
    
    0 讨论(0)
  • 2020-11-22 04:05

    In my case, I did this

      const eventId = event.id;
      User.findByIdAndUpdate(id, { $push: { createdEvents: eventId } }).exec();
    
    0 讨论(0)
  • 2020-11-22 04:05

    I ran into this issue as well. My fix was to create a child schema. See below for an example for your models.

    ---- Person model

    const mongoose = require('mongoose');
    const SingleFriend = require('./SingleFriend');
    const Schema   = mongoose.Schema;
    
    const productSchema = new Schema({
      friends    : [SingleFriend.schema]
    });
    
    module.exports = mongoose.model('Person', personSchema);
    

    ***Important: SingleFriend.schema -> make sure to use lowercase for schema

    --- Child schema

    const mongoose = require('mongoose');
    const Schema   = mongoose.Schema;
    
    const SingleFriendSchema = new Schema({
      Name: String
    });
    
    module.exports = mongoose.model('SingleFriend', SingleFriendSchema);
    
    0 讨论(0)
  • 2020-11-22 04:15

    Assuming, var friend = { firstName: 'Harry', lastName: 'Potter' };

    There are two options you have:

    Update the model in-memory, and save (plain javascript array.push):

    person.friends.push(friend);
    person.save(done);
    

    or

    PersonModel.update(
        { _id: person._id }, 
        { $push: { friends: friend } },
        done
    );
    

    I always try and go for the first option when possible, because it'll respect more of the benefits that mongoose gives you (hooks, validation, etc.).

    However, if you are doing lots of concurrent writes, you will hit race conditions where you'll end up with nasty version errors to stop you from replacing the entire model each time and losing the previous friend you added. So only go to the former when it's absolutely necessary.

    0 讨论(0)
  • 2020-11-22 04:16

    An easy way to do that is to use the following:

    var John = people.findOne({name: "John"});
    John.friends.push({firstName: "Harry", lastName: "Potter"});
    John.save();
    
    0 讨论(0)
  • 2020-11-22 04:24

    First I tried this code

    const peopleSchema = new mongoose.Schema({
      name: String,
      friends: [
        {
          firstName: String,
          lastName: String,
        },
      ],
    });
    const People = mongoose.model("person", peopleSchema);
    const first = new Note({
      name: "Yash Salvi",
      notes: [
        {
          firstName: "Johnny",
          lastName: "Johnson",
        },
      ],
    });
    first.save();
    const friendNew = {
      firstName: "Alice",
      lastName: "Parker",
    };
    People.findOneAndUpdate(
      { name: "Yash Salvi" },
      { $push: { friends: friendNew } },
      function (error, success) {
        if (error) {
          console.log(error);
        } else {
          console.log(success);
        }
      }
    );
    

    But I noticed that only first friend (i.e. Johhny Johnson) gets saved and the objective to push array element in existing array of "friends" doesn't seem to work as when I run the code , in database in only shows "First friend" and "friends" array has only one element ! So the simple solution is written below

    const peopleSchema = new mongoose.Schema({
      name: String,
      friends: [
        {
          firstName: String,
          lastName: String,
        },
      ],
    });
    const People = mongoose.model("person", peopleSchema);
    const first = new Note({
      name: "Yash Salvi",
      notes: [
        {
          firstName: "Johnny",
          lastName: "Johnson",
        },
      ],
    });
    first.save();
    const friendNew = {
      firstName: "Alice",
      lastName: "Parker",
    };
    People.findOneAndUpdate(
      { name: "Yash Salvi" },
      { $push: { friends: friendNew } },
      { upsert: true }
    );
    

    Adding "{ upsert: true }" solved problem in my case and once code is saved and I run it , I see that "friends" array now has 2 elements ! The upsert = true option creates the object if it doesn't exist. default is set to false.

    if it doesn't work use below snippet

    People.findOneAndUpdate(
      { name: "Yash Salvi" },
      { $push: { friends: friendNew } },
    ).exec();
    
    0 讨论(0)
提交回复
热议问题