我有这段代码
var MongoClient = require('mongodb').MongoClient;
var url = 'mongodb://localhost:27017/clboTest';
// this could have comed from a form from the browser
var objToInsert = {
_id: 2,
price: 20000,
name: stdin,
description: "20 carat gold ring. ",
//schoolID: { name: 'RUC', address: 'Roskilde', country: 'Denmark' }
};
MongoClient.connect(url, function (err, db) {
var collection = db.collection('products');
collection.insert(objToInsert, function (err, result) {
console.log(result);
db.close();
});
});
我不想让信息硬编码(例如价格,名称)。如何在控制台中输入新内容,而不是反复使用新信息对insert.js文件进行核心处理?
答案 0 :(得分:1)
您可以使用名为readline-sync的包。然后,您可以在插入对象之前等待用户输入:
var readlineSync = require('readline-sync');
var name = readlineSync.question('name: ');
var price = readlineSync.questionInt('price: ');
console.log(name);
console.log(price);
var objToInsert = {
_id: 2,
price: price,
name: name,
description: "20 carat gold ring. ",
//schoolID: { name: 'RUC', address: 'Roskilde', country: 'Denmark' }
};
祝你好运!