使用mongodb和node.js

时间:2016-04-01 11:31:43

标签: node.js mongodb

我在特定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();
  });
});

1 个答案:

答案 0 :(得分:2)

插入后,您必须从数据库中请求用户。 例如根据您的代码,以下内容应该有效:

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);
      });
    });
};