mongodb insertone javascript code example
Example 1: insert into mongodb node js
const mongodb = require('mongodb');
const MongoClient = mongodb.MongoClient;
const connectionURl = 'mongodb://127.0.0.1:27017';
const databaseName = 'task-manager';
MongoClient.connect(
connectionURl,
{ useNewUrlParser: true },
(error, client) => {
if (error) {
return console.log('unable to connect to database');
}
const db = client.db(databaseName);
db.collection('users').insertOne({
name: 'user',
age: 24,
});
}
);
Example 2: mongodb js get id of inserted
collection.insert(objToInsert, function (err, result){
if(err)console.log(err);
else {
console.log(result["ops"][0]["_id"]);
}
});