简体   繁体   中英

MongoDB References Not Saving (Mongoose)

So I have encountered a strange problem that has been driving me crazy. I have a schema for Stores which represent storefronts that carry the products of certain Manufacturers which I also have a schema for. One of the properties of the Store schema is an array of Manufacturer objects referenced by ObjectId.

Basically, what I want to accomplish is that when a new Store document is created, I want to go through all of the existing Manufacturer documents, and add the _id property of each one to the reference array in the Store document.

The strangest thing is, that after I call the .save() method on the newly created Store model after pushing all the _id 's onto the array, the debugging print out shows that the result saved exactly how I want it. However, when I go to make a cURL call to pull the record from my database, the manufacturers array is completely empty and none of the ObjectId's become populated with their reference.

I have no idea where to go from here, can anybody help?

Thanks

Schema Definitions:

var Schema = mongoose.Schema;

//create a schema for database
var storeSchema = new Schema({
  "number": String,
  "state": String,
  "zip": String,
  "city": String,
  "street": String,
  "manufacturers": [{
    "type": mongoose.Schema.Types.Mixed,
    "ref": "Manufacturer"
  }]
});

var manufacturerSchema = new Schema({
  "name": String,
  "country": String,
  "products": [{
    "type": mongoose.Schema.Types.ObjectId,
    "ref": "Product"
  }]
});

var Product = mongoose.model("Product", productSchema);
var Manufac = mongoose.model("Manufacturer", manufacturerSchema);

Creating a Store Document:

app.put("/api/v1.0/stores", function(req, res){
  console.log("PUT request received at /stores.");
  if(Object.keys(req.body).length < 5){
     //not enough parameters
    console.log("Not enough parameters were supplied.");
    res.sendStatus(400);
  }
  //create a new database product document and save to database
  var savedID;
  var params = req.body;
  var tmpStore = new Store({
    "number": params.number,
    "state": params.state,
    "zip": params.zip,
    "city": params.city,
    "street": params.street
  });
  //find all manufacturers 
  Manufac.find({}, function(err, result){
    result.forEach(function(value){
      tmpStore.manufacturers.push(value._id);
    });
  });

  tmpStore.save(function(err, result){
    if(err) {
      console.log("Error PUTing store!"); return;
    }
      console.log("Saved successfully: " + result);
  });
  res.sendStatus(200);
});

Output:

App listening on port 8080.
PUT request received at /stores.
Saved successfully: { __v: 0,
  number: '1',
  state: 'OR',
  zip: '97333',
  city: 'Corvallis',
  street: '1680 Washington St.',
  _id: 578df6a679e28aea6b84bec8,
  manufacturers:
   [ 578dae80a8f8ec3266a5d956,
     578dd1918caa17b467b7caee,
     578dd19f8caa17b467b7caef,
     578dd1bd8caa17b467b7caf0 ] }

JSON from cURL GET

{
    "_id": "578df6a679e28aea6b84bec8",
    "number": "1",
    "state": "OR",
    "zip": "97333",
    "city": "Corvallis",
    "street": "1680 Washington St.",
    "__v": 0,
    "manufacturers": []
}

Server-Side GET Request Code:

app.get("/api/v1.0/stores", function(req, res) {
  console.log("Get received at /stores");
  Store
      .find({})
      .populate("manufacturers")
      .exec(function(err, result){
        if(err){
          console.log("Error fetching stores!"); return;
        }
        res.json(result);
      });
  });

I think you should have tmpStore.save inside find function. As it is asynchronous it will move to save function before find functions callback.

I think you should have something like

Manufac.find({}, function(err, result){
    result.forEach(function(value){
      tmpStore.manufacturers.push(value._id);
    });
tmpStore.save(function(err, result){
    if(err) {
      console.log("Error PUTing store!"); return;
    }
      console.log("Saved successfully: " + result);
  });
  });

I think this should work.

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