簡體   English   中英

無法使用mongodb和node.js從其他集合中獲取ID

[英]Not getting id from other collection using mongodb and node.js

我在特定userId下添加產品,但未從其他集合中獲取userId

api.js

var insertDocument = function(db, callback) {
   db.collection('proInfo').insertOne( {
        "Product_Name": json.Product_Name,
        "Brand": json.Brand,
        "Color": json.Color,
        "Image": json.Image,
        "Price": json.Price,
        "Rating": json.Rating,
        "Description": json.Description,
        "Category": json.Category,
        "Url": urla,
        **"userId":db.collection('users').findOne()[0]._id,**
   }, function(err, result) {
        assert.equal(err, null);
        console.log("Inserted a document into the proInfo collection.");
        callback(result);
  });
};

MongoClient.connect(url, function(err, db) {
  assert.equal(null, err);
  insertDocument(db, function() {
      db.close();
  });
});

插入數據庫后,您必須從datbase中請求用戶。 例如,根據您的代碼,以下應該工作:

var insertDocument = function(db, callback) {
    // Based on your code we assume that you have only one user in the database. Otherwise you have to do a find for a specific user.
    db.collection('users').findOne(function (err, user) {
       if (err) { return callback(err); }
       db.collection('proInfo').insertOne( {
            "Product_Name": json.Product_Name,
            "Brand": json.Brand,
            "Color": json.Color,
            "Image": json.Image,
            "Price": json.Price,
            "Rating": json.Rating,
            "Description": json.Description,
            "Category": json.Category,
            "Url": urla,
            "userId": user._id
       }, function(err, result) {
            assert.equal(err, null);
            console.log("Inserted a document into the proInfo collection.");
            // Below I am passing the error as a first param to your callback. You can implemented as you wish, but it is a convention to use error as a first param.
            callback(err, result);
      });
    });
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM