[英]Not getting id from other collection using mongodb and node.js
I am adding products under particular userId
but not getting userId
from other collection. 我在特定
userId
下添加产品,但未从其他集合中获取userId
。
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();
});
});
You have to request the user from the datbase after inserting it. 插入数据库后,您必须从datbase中请求用户。 eg based on your code the following should work:
例如,根据您的代码,以下应该工作:
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.