繁体   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