Cập nhật nút js mongodb bởi _id

Lỗi là do chúng tôi đang nhập tệp JSON có “_id” là Chuỗi chứ không phải ObjectId, bạn có thể thực hiện các bước sau (tôi đã tìm thấy tệp này trên StackOverflow và sao chép mọi thứ, xin lỗi tôi không có liên kết rn)

Ngay từ đầu.
Kiểm tra cơ sở dữ liệu MongoDB của bạn, nếu _id được lưu dưới dạng Chuỗi, thì không thể tìm thấy findById(id) vì nó xác định ObjectId. Nếu bạn đã sử dụng cơ sở dữ liệu nhập bằng cách sử dụng lệnh mongoimport và bao gồm _id trong JSON.

Giải pháp 1

sửa đổi JSON của bạn và đối với từng tài liệu, hãy thay đổi _id chẳng hạn

_Tôi. “5a68fde3f09ad7646ddec17e” vào phần sau và chạy lại mongoimport

"_id": { "$oid": "5a68fde3f09ad7646ddec17e" }

Giải pháp 2

xóa _id trong tệp JSON, thả bộ sưu tập và nhập lại. Mongo sẽ tự động tạo _id

Sau bất kỳ giải pháp nào ở trên, findById(“id”) sẽ hoạt động

Thứ hai.
Cụ thể trong những trường hợp như vậy khi các phần tử _id của bạn là chuỗi, có thể nên sử dụng gói MongoDB. npm tôi MongoDB

var MongoClient = require(‘mongodb’). MongoClient;
var url = “mongodb. //máy chủ cục bộ. 27017/”;

MongoClient. connect(url, function (err, db) {
if (err) throw err;
var dbo = db. db(“your_db_name”);
dbo. bộ sưu tập(“fruits_collection”)
. tìm ID. ‘5a1cf77920701c1f0aafb85e’})
//. tìm ID. '5a1cf77920701c1f0aafb85e'}, { phép chiếu. { _Tôi. 0, tên. 1, màu sắc. 1} }) // để chọn các cột cụ thể mong muốn
. toArray(function (err, result) {
if (err) throw err;
bàn điều khiển. log(kết quả);
db. close();
});
});

Mã đơn giản ở trên, giả sử bạn tự quản lý việc xử lý lỗi, thông qua thử bắt hoặc gửi 404 dưới dạng mã trạng thái hoặc chuyển hướng đến mẫu trang lỗi, tùy thuộc vào việc mã có được nhúng trong trình xử lý tuyến Express hay không

Tôi đang cố cập nhật "ObjectId" từ giao diện người dùng lên cơ sở dữ liệu của mình nhưng có vẻ như nó không cập nhật. Nếu tôi thêm một dữ liệu mới từ ui vào db, nó sẽ hoạt động tốt. tuy nhiên nó không hoạt động khi tôi muốn cập nhật dữ liệu đó

Tôi đã thử hầu hết mọi thứ nhưng có vẻ như nó không hoạt động. Bất kỳ trợ giúp sẽ được thực sự đánh giá cao. Cảm ơn

Đây là máy chủ của tôi. mã js

    let express = require('express')
let MongoClient = require('mongodb').MongoClient
let ObjectId = require('mongodb').ObjectId;


let app = express()
let db
app.use(express.static('public'))

let connectionString = "mongodb+srv://todoAppUser:(HIDDEN)/TodoAPP?retryWrites=true"
MongoClient.connect(connectionString, {useNewUrlParser: true, useUnifiedTopology: true}, function(err, client) {
  db = client.db()
  app.listen(3000)

})
app.use(express.json())
app.use(express.urlencoded({extended: false}))

app.get('/', function(req, res) {
  db.collection('items').find().toArray(function(err, items) {
    res.send(`
  
  
    
    
    Simple To-Do App
    
  
  
    

To-Do App

Add New Item

    ${items.map(function(item) { return `
  • ${item.text}

    Edit Delete

  • ` }).join('')}

`) }) }) app.post('/create-item', function(req, res) { db.collection('items').insertOne({text: req.body.item}, function() { res.redirect('/') }) }) app.post('/update-item', function(req, res) { db.collection('items').findOneAndUpdate({_id: new mongodb.ObjectId(req.body.id)}, {$set: {text: req.body.text}}, function() { res.send("Success") }) })

và đây là trình duyệt của tôi. js

   document.addEventListener("click", function(e) {
  if (e.target.classList.contains("edit-me")) {
    let userInput = prompt("Enter your desired new text")
      axios.post('/update-item', {text: userInput, _id: e.target.getAttribute("data-id")}).then(function () {
        // do something interesting here in the next video
      }).catch(function() {
        console.log("Please try again later.")
      })
    }
})

tôi đánh giá cao bất kỳ sự giúp đỡ. Cảm ơn

- stackoverflow. com

ghi bàn. 0

Tôi cũng gặp phải vấn đề tương tự và giải pháp này phù hợp với tôi. nó sẽ như thế này

app.post('/update-item', function(req, res) {
db.collection('items').findOneAndUpdate({_id: ObjectId(req.body.id)}, {$set: {text: req.body.text}}, function() {
  res.send("Success")
})

})

thay vì

app.post('/update-item', function(req, res) {
  db.collection('items').findOneAndUpdate({_id: new mongodb.ObjectId(req.body.id)}, {$set: {text: req.body.text}}, function() {
    res.send("Success")
  })
})

Thêm câu hỏi với thẻ tương tự

Hàm findOneAndUpdate() trong Mongoose có nhiều trường hợp sử dụng. Bạn nên sử dụng save() để cập nhật tài liệu nếu có thể, nhưng có một số trường hợp bạn cần sử dụng findOneAndUpdate(). Trong hướng dẫn này, bạn sẽ thấy cách sử dụng findOneAndUpdate() và tìm hiểu khi nào bạn cần sử dụng nó

Như tên ngụ ý, findOneAndUpdate() tìm tài liệu đầu tiên khớp với một

    let express = require('express')
let MongoClient = require('mongodb').MongoClient
let ObjectId = require('mongodb').ObjectId;


let app = express()
let db
app.use(express.static('public'))

let connectionString = "mongodb+srv://todoAppUser:(HIDDEN)/TodoAPP?retryWrites=true"
MongoClient.connect(connectionString, {useNewUrlParser: true, useUnifiedTopology: true}, function(err, client) {
  db = client.db()
  app.listen(3000)

})
app.use(express.json())
app.use(express.urlencoded({extended: false}))

app.get('/', function(req, res) {
  db.collection('items').find().toArray(function(err, items) {
    res.send(`
  
  
    
    
    Simple To-Do App
    
  
  
    

To-Do App

Add New Item

    ${items.map(function(item) { return `
  • ${item.text}

    Edit Delete

  • ` }).join('')}

`) }) }) app.post('/create-item', function(req, res) { db.collection('items').insertOne({text: req.body.item}, function() { res.redirect('/') }) }) app.post('/update-item', function(req, res) { db.collection('items').findOneAndUpdate({_id: new mongodb.ObjectId(req.body.id)}, {$set: {text: req.body.text}}, function() { res.send("Success") }) })
0 nhất định, áp dụng một
    let express = require('express')
let MongoClient = require('mongodb').MongoClient
let ObjectId = require('mongodb').ObjectId;


let app = express()
let db
app.use(express.static('public'))

let connectionString = "mongodb+srv://todoAppUser:(HIDDEN)/TodoAPP?retryWrites=true"
MongoClient.connect(connectionString, {useNewUrlParser: true, useUnifiedTopology: true}, function(err, client) {
  db = client.db()
  app.listen(3000)

})
app.use(express.json())
app.use(express.urlencoded({extended: false}))

app.get('/', function(req, res) {
  db.collection('items').find().toArray(function(err, items) {
    res.send(`
  
  
    
    
    Simple To-Do App
    
  
  
    

To-Do App

Add New Item

    ${items.map(function(item) { return `
  • ${item.text}

    Edit Delete

  • ` }).join('')}

`) }) }) app.post('/create-item', function(req, res) { db.collection('items').insertOne({text: req.body.item}, function() { res.redirect('/') }) }) app.post('/update-item', function(req, res) { db.collection('items').findOneAndUpdate({_id: new mongodb.ObjectId(req.body.id)}, {$set: {text: req.body.text}}, function() { res.send("Success") }) })
1 và trả lại tài liệu. Theo mặc định, findOneAndUpdate() trả về tài liệu như trước khi áp dụng
    let express = require('express')
let MongoClient = require('mongodb').MongoClient
let ObjectId = require('mongodb').ObjectId;


let app = express()
let db
app.use(express.static('public'))

let connectionString = "mongodb+srv://todoAppUser:(HIDDEN)/TodoAPP?retryWrites=true"
MongoClient.connect(connectionString, {useNewUrlParser: true, useUnifiedTopology: true}, function(err, client) {
  db = client.db()
  app.listen(3000)

})
app.use(express.json())
app.use(express.urlencoded({extended: false}))

app.get('/', function(req, res) {
  db.collection('items').find().toArray(function(err, items) {
    res.send(`
  
  
    
    
    Simple To-Do App
    
  
  
    

To-Do App

Add New Item

    ${items.map(function(item) { return `
  • ${item.text}

    Edit Delete

  • ` }).join('')}

`) }) }) app.post('/create-item', function(req, res) { db.collection('items').insertOne({text: req.body.item}, function() { res.redirect('/') }) }) app.post('/update-item', function(req, res) { db.collection('items').findOneAndUpdate({_id: new mongodb.ObjectId(req.body.id)}, {$set: {text: req.body.text}}, function() { res.send("Success") }) })
1

Bạn nên đặt tùy chọn findOneAndUpdate()0 thành findOneAndUpdate()1 để trả lại tài liệu sau khi áp dụng

    let express = require('express')
let MongoClient = require('mongodb').MongoClient
let ObjectId = require('mongodb').ObjectId;


let app = express()
let db
app.use(express.static('public'))

let connectionString = "mongodb+srv://todoAppUser:(HIDDEN)/TodoAPP?retryWrites=true"
MongoClient.connect(connectionString, {useNewUrlParser: true, useUnifiedTopology: true}, function(err, client) {
  db = client.db()
  app.listen(3000)

})
app.use(express.json())
app.use(express.urlencoded({extended: false}))

app.get('/', function(req, res) {
  db.collection('items').find().toArray(function(err, items) {
    res.send(`
  
  
    
    
    Simple To-Do App
    
  
  
    

To-Do App

Add New Item

    ${items.map(function(item) { return `
  • ${item.text}

    Edit Delete

  • ` }).join('')}

`) }) }) app.post('/create-item', function(req, res) { db.collection('items').insertOne({text: req.body.item}, function() { res.redirect('/') }) }) app.post('/update-item', function(req, res) { db.collection('items').findOneAndUpdate({_id: new mongodb.ObjectId(req.body.id)}, {$set: {text: req.body.text}}, function() { res.send("Success") }) })
1

Mongoose's findOneAndUpdate() hơi khác so với MongoDB Node. js's findOneAndUpdate() vì nó trả về chính tài liệu, không phải đối tượng kết quả

Để thay thế cho tùy chọn findOneAndUpdate()0, bạn cũng có thể sử dụng tùy chọn findOneAndUpdate()6. findOneAndUpdate()7 tương đương với findOneAndUpdate()8. Tùy chọn findOneAndUpdate()6 tồn tại để thống nhất với Nút MongoDB. js của trình điều khiển findOneAndUpdate(), có tùy chọn tương tự

Ngoại trừ một upert chưa được lập chỉ mục, findOneAndUpdate() là nguyên tử. Điều đó có nghĩa là bạn có thể giả định rằng tài liệu không thay đổi giữa thời điểm MongoDB tìm thấy tài liệu và khi nó cập nhật tài liệu, trừ khi bạn đang thực hiện upsert

Ví dụ: nếu bạn đang sử dụng save() để cập nhật tài liệu, thì tài liệu đó có thể thay đổi trong MongoDB giữa khi bạn tải tài liệu bằng save()3 và khi bạn lưu tài liệu bằng save() như hiển thị bên dưới. Đối với nhiều trường hợp sử dụng, điều kiện cuộc đua save() không phải là vấn đề. Nhưng bạn có thể giải quyết nó với findOneAndUpdate() (hoặc giao dịch) nếu bạn cần

Sử dụng tùy chọn save()7, bạn có thể sử dụng findOneAndUpdate() làm thao tác tìm và nâng cấp. Upsert hoạt động giống như một findOneAndUpdate() bình thường nếu nó tìm thấy một tài liệu phù hợp với

    let express = require('express')
let MongoClient = require('mongodb').MongoClient
let ObjectId = require('mongodb').ObjectId;


let app = express()
let db
app.use(express.static('public'))

let connectionString = "mongodb+srv://todoAppUser:(HIDDEN)/TodoAPP?retryWrites=true"
MongoClient.connect(connectionString, {useNewUrlParser: true, useUnifiedTopology: true}, function(err, client) {
  db = client.db()
  app.listen(3000)

})
app.use(express.json())
app.use(express.urlencoded({extended: false}))

app.get('/', function(req, res) {
  db.collection('items').find().toArray(function(err, items) {
    res.send(`
  
  
    
    
    Simple To-Do App
    
  
  
    

To-Do App

Add New Item

    ${items.map(function(item) { return `
  • ${item.text}

    Edit Delete

  • ` }).join('')}

`) }) }) app.post('/create-item', function(req, res) { db.collection('items').insertOne({text: req.body.item}, function() { res.redirect('/') }) }) app.post('/update-item', function(req, res) { db.collection('items').findOneAndUpdate({_id: new mongodb.ObjectId(req.body.id)}, {$set: {text: req.body.text}}, function() { res.send("Success") }) })
0. Tuy nhiên, nếu không có tài liệu nào khớp với
    let express = require('express')
let MongoClient = require('mongodb').MongoClient
let ObjectId = require('mongodb').ObjectId;


let app = express()
let db
app.use(express.static('public'))

let connectionString = "mongodb+srv://todoAppUser:(HIDDEN)/TodoAPP?retryWrites=true"
MongoClient.connect(connectionString, {useNewUrlParser: true, useUnifiedTopology: true}, function(err, client) {
  db = client.db()
  app.listen(3000)

})
app.use(express.json())
app.use(express.urlencoded({extended: false}))

app.get('/', function(req, res) {
  db.collection('items').find().toArray(function(err, items) {
    res.send(`
  
  
    
    
    Simple To-Do App
    
  
  
    

To-Do App

Add New Item

    ${items.map(function(item) { return `
  • ${item.text}

    Edit Delete

  • ` }).join('')}

`) }) }) app.post('/create-item', function(req, res) { db.collection('items').insertOne({text: req.body.item}, function() { res.redirect('/') }) }) app.post('/update-item', function(req, res) { db.collection('items').findOneAndUpdate({_id: new mongodb.ObjectId(req.body.id)}, {$set: {text: req.body.text}}, function() { res.send("Success") }) })
0, MongoDB sẽ chèn một tài liệu bằng cách kết hợp
    let express = require('express')
let MongoClient = require('mongodb').MongoClient
let ObjectId = require('mongodb').ObjectId;


let app = express()
let db
app.use(express.static('public'))

let connectionString = "mongodb+srv://todoAppUser:(HIDDEN)/TodoAPP?retryWrites=true"
MongoClient.connect(connectionString, {useNewUrlParser: true, useUnifiedTopology: true}, function(err, client) {
  db = client.db()
  app.listen(3000)

})
app.use(express.json())
app.use(express.urlencoded({extended: false}))

app.get('/', function(req, res) {
  db.collection('items').find().toArray(function(err, items) {
    res.send(`
  
  
    
    
    Simple To-Do App
    
  
  
    

To-Do App

Add New Item

    ${items.map(function(item) { return `
  • ${item.text}

    Edit Delete

  • ` }).join('')}

`) }) }) app.post('/create-item', function(req, res) { db.collection('items').insertOne({text: req.body.item}, function() { res.redirect('/') }) }) app.post('/update-item', function(req, res) { db.collection('items').findOneAndUpdate({_id: new mongodb.ObjectId(req.body.id)}, {$set: {text: req.body.text}}, function() { res.send("Success") }) })
0 và
    let express = require('express')
let MongoClient = require('mongodb').MongoClient
let ObjectId = require('mongodb').ObjectId;


let app = express()
let db
app.use(express.static('public'))

let connectionString = "mongodb+srv://todoAppUser:(HIDDEN)/TodoAPP?retryWrites=true"
MongoClient.connect(connectionString, {useNewUrlParser: true, useUnifiedTopology: true}, function(err, client) {
  db = client.db()
  app.listen(3000)

})
app.use(express.json())
app.use(express.urlencoded({extended: false}))

app.get('/', function(req, res) {
  db.collection('items').find().toArray(function(err, items) {
    res.send(`
  
  
    
    
    Simple To-Do App
    
  
  
    

To-Do App

Add New Item

    ${items.map(function(item) { return `
  • ${item.text}

    Edit Delete

  • ` }).join('')}

`) }) }) app.post('/create-item', function(req, res) { db.collection('items').insertOne({text: req.body.item}, function() { res.redirect('/') }) }) app.post('/update-item', function(req, res) { db.collection('items').findOneAndUpdate({_id: new mongodb.ObjectId(req.body.id)}, {$set: {text: req.body.text}}, function() { res.send("Success") }) })
1 như hình bên dưới

Tùy chọn `rawResult`

Mongoose biến đổi kết quả của findOneAndUpdate() theo mặc định. nó trả về tài liệu cập nhật. Điều đó gây khó khăn cho việc kiểm tra xem một tài liệu đã được cập nhật hay chưa. Để có được tài liệu cập nhật và kiểm tra xem MongoDB đã cập nhật một tài liệu mới trong cùng một thao tác hay chưa, bạn có thể đặt cờ findOneAndUpdate()5 để khiến Mongoose trả về kết quả thô từ MongoDB

Làm cách nào để cập nhật dữ liệu theo id trong MongoDB?

Các bước thực hiện như sau. .
Bước 1. Ở bước đầu tiên, bạn cần lưu trữ ObjectId vào một biến. anyVariableName=db. .
Bước 2. Trong bước thứ hai, bạn cần đặt id mới. .
Bước 3. Ở bước thứ ba, bạn cần chèn id mới vào tài liệu. .
Bước 4. Ở bước thứ tư, bạn cần xóa id cũ

Làm cách nào để cập nhật dữ liệu trong MongoDB bằng nút JS?

Bạn có thể cập nhật một bản ghi hoặc tài liệu như nó được gọi trong MongoDB, bằng cách sử dụng phương thức updateOne() . Tham số đầu tiên của phương thức updateOne() là một đối tượng truy vấn xác định tài liệu nào sẽ cập nhật. Ghi chú. Nếu truy vấn tìm thấy nhiều bản ghi, thì chỉ bản ghi đầu tiên được cập nhật.

Chúng tôi có thể thay đổi _ID trong MongoDB không?

Nếu vậy, câu trả lời là có, bạn có thể đặt thuộc tính _id thành một giá trị thuộc bất kỳ loại nào ngoại trừ mảng , theo https. // tài liệu. mongodb. com/thủ công/lõi/tài liệu/.

_ID trong MongoDB là gì?

Theo mặc định, MongoDB tạo một chỉ mục duy nhất trên trường _id trong quá trình tạo bộ sưu tập. Trường _id luôn là trường đầu tiên trong tài liệu . Nếu máy chủ nhận tài liệu không có trường _id trước thì máy chủ sẽ chuyển trường này về đầu.