简体   繁体   English

MongoDB引用不保存(猫鼬)

[英]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. Store架构的一个属性是ObjectId引用的Manufacturer对象数组。

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. 基本上,我想要实现的是,当创建新的Store文档时,我想查看所有现有的Manufacturer文档,并将每个文档的_id属性添加到Store文档中的引用数组。

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. 最奇怪的是,在将所有_id推入数组后,在新创建的Store模型上调用.save()方法之后,调试打印输出显示结果完全保存了我想要的方式。 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. 但是,当我进行cURL调用以从我的数据库中提取记录时,制造商数组完全为空,并且没有任何ObjectId被填充其引用。

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 来自cURL GET的JSON

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

Server-Side GET Request Code: 服务器端GET请求代码:

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. 我想你应该在find函数里面有tmpStore.save As it is asynchronous it will move to save function before find functions callback. 因为它是异步的,所以在find函数回调之前它将移动到save函数。

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. 我认为这应该有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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