簡體   English   中英

我的本地MongoDB實例未通過Express和Mongoose保存數據

[英]My local MongoDB instance is not saving data via Express and Mongoose

因此,這在控制台中有效,但無法寫入數據庫。 當我重新啟動服務器時,數據將重置。 它從數據庫讀取就很好,只是不保存。 我正在運行mongo shell並清楚地從中獲取數據,只是沒有按我的意願更新或創建數據。 這是我的server.js文件中的代碼:

    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!!
    */

無論如何, foundObjects不會受到save()函數的影響,因此日志是無用的。

我不知道您為什么要查找bkyes每個文檔並取出第一個文檔。 您通常會發現帶有某些條件的文檔,通常是_id字段。

無論如何,這是findOneAndUpdate()的示例:

bkyes
  .findOneAndUpdate({
    // Conditions
    _id: '00001'
  }, {
    // Set which fields to update
    vote: 5 
  })
  .exec(function(err, foundObject) {
    if (err) {
      // Error handler here
    }

    // Do something when update successfully
  });

注意: foundObject是更新之前的對象。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM