简体   繁体   中英

Adding Objects to Array of Objects in a Document using Mongoose.js

I've looked in stackoverflow, however I've not found the answer. I'm trying to add Object to a New(empty) Array in my local mongodb that is not a duplicate. I also want to update this Array with other Objects.

I've looked at $push and $addToSet, the examples are using an "id" (_id) which wouldn't be created until I add my first Object.

I'm using Node.js, Mongoose.js, Mongodb, Express.js.

My Schema is:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var barSchema = new Schema({
    location: [{
           name: String,
           city: String,
           total: Number
              }]     
           });
var Bar = mongoose.model('Bar', barSchema);
module.exports = Bar;

I've tried to use this;

       var newBar = bar({ 
           location: [{ "name": req.body.bar, "city": req.body.city, "total": 0 }] });
           newBar.save(function(err) {
              if (err) throw err;
        });

I've also used the $push with success but in this case I've not got an "id"

        user.findByIdAndUpdate(req.user._id, { $push: { 
                               barlist: { "name": req.body.bar, 
                                          "rsvp": true } } },           
                                 function(err, user) { });

Which gives back this;

     {
      "_id" : ObjectId("######"),
      "location" : [
       {
           "name" : "1st Bar",
           "city" : "Boston",
           "total" : 0,
           "_id" : ObjectId("#########")
        }
                ],
         "__v" : 0
      }
     {
      "_id" : ObjectId("######"),
      "location" : [
       {
           "name" : "2nd Bar",
           "city" : "Boston",
           "total" : 0,
           "_id" : ObjectId("#########")
        }
                ],
         "__v" : 0
      }

However I am trying to get this;

      {
      "_id" : ObjectId("#######"),
      "location" : [
        {
           "name" : "Biddy Early's",
           "city" : "Boston",
           "total" : 0
        },
        {
           "name" : "Some Bar Name",
           "city" : "Boston",
           "total" : 0
        }
                  ]
      }

Please know there may be better ways to do this, but... The first thing you want to do in this case is create a new instance of your schema or 'model' . Based on what your code looks like you might want to consider something like this;

        var newBar = bar({
            "city": req.body.city,
            location: [{
                "bar": req.body.bar,
                "total": 0
            }]
        });
        newBar.save(function(err) {
            if (err) throw err;
        });

Since if you are looking for bars or restaurants in the same city you might want to have a common key/value pair to '.find()' or '.update()' depending on what you want to do with it.

From here, you will want to look into what you mentioned before with '$addToSet' so that you wouldn't be adding duplicate bars to your 'location' array. So for instance;

        bar.findOneAndUpdate({'city':req.body.city}, 
              {'$addToSet': { location: { 
                                 'bar': req.body.bar, 'total': 0 } } },
                        function(err, b) {
                            if (err) throw err;
                                console.log(b);
                            });

Consider using a strategy like if/else to determine if the city name exists, if it does then you would utilize the '$addToSet'. Else, if it didn't exist you would utilize the new model like the example I used.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM