所以這是在控制檯中工作,但不寫入數據庫。當我重新啓動服務器時,數據只是重置。它從數據庫讀取就好了,只是沒有保存。我正在運行mongo shell,並明確地從中取出數據,而不是像我想要的那樣更新或創建數據。下面是我的server.js文件中的代碼:我的本地MongoDB實例沒有通過Express和Mongoose保存數據
var express = require('express');
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var bodyParser = require('body-parser');
var app = express();
mongoose.Promise = global.Promise;
mongoose.connect('mongodb://localhost:27017/food');
//Allow all requests from all domains & localhost
app.all('/*', function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With, Content-Type, Accept");
res.header("Access-Control-Allow-Methods", "POST, GET");
next();
});
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
var usersSchema = new Schema({
_id: String,
id: String,
vote: Number
});
var bkyes = mongoose.model('bkyes', usersSchema);
app.post('/bkyes', function(req, res, next) {
bkyes.find({}, function(err, foundObject) {
console.log(foundObject); //Print pre-update
var found = foundObject[0];
found.vote = req.body.vote; //Passing in the number 5 here(was -1 before)
found.save(function(err) {
console.log(foundObject); //Print post-update
});
});
});
app.listen(3000);
/*
The console.log pre-update:
[ { _id: '582b2da0b983b79b61da3f9c', id: 'Burger King', vote: -1 } ]
^
The console.log post-update:
[ { _id: '582b2da0b983b79b61da3f9c', id: 'Burger King', vote: 5 } ]
^
However this data does NOT write to the db and just resets when you restart the server!!
*/
檢查你'req.body.vote',這是一個數字嗎? – Khang
它是從前端傳入的。正如你可以在底部的註釋部分看到的,它正在更新Mongo BSON,而不是將它保存到數據庫。當我檢查shell時,它並未真正寫入。 – jdev99
使用findOneAndUpdate()而不是查找然後保存 – Sam