最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Why doesn't MongoDB save my properties - Stack Overflow

programmeradmin4浏览0评论

I'm populating my DB with some dummy data where I'm trying to add a user. A user object is created but none of the properties are save... whats up?

app.get('/setup', function (req, res) {

    User.findOne({ name: "Nick" }, function (err, user) {

        if (user == undefined) {

            var nick = new User({
                name: "Nick",
            }).save();

            res.json({ "success": true, "msg": "user created" });
        } else {
            res.json({ "success": true, "msg": "user existed" });
        }
    });
});

calling this returns "user created". Here is my method to output all users:

app.get('/users', function(req, res) {

    User.find({}, function(err, user) {
        res.json(user);
    });
});

The output here is

[
  {
    "_id": "565772db5f6f2d1c25e999be",
    "__v": 0
  },
  {
    "_id": "5657734ba859fefc1dca77db",
    "__v": 0
  },
  {
    "_id": "5657738ba859fefc1dca77dc",
    "__v": 0
  },
  {
    "_id": "565774f1cf99a2b81fca1e7f",
    "__v": 0
  },
  {
    "_id": "565775f0cf99a2b81fca1e80",
    "__v": 0
  }
]

Where I've tried to add "Nick" a couple of times noe... any input? :D

My Mongoose model, located in its own Model.js file with other models:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

// set up a mongoose model and pass it using module.exports
module.exports = mongoose.model('User', new Schema({ 
    name: String, 
    password: String, 
}));

I'm populating my DB with some dummy data where I'm trying to add a user. A user object is created but none of the properties are save... whats up?

app.get('/setup', function (req, res) {

    User.findOne({ name: "Nick" }, function (err, user) {

        if (user == undefined) {

            var nick = new User({
                name: "Nick",
            }).save();

            res.json({ "success": true, "msg": "user created" });
        } else {
            res.json({ "success": true, "msg": "user existed" });
        }
    });
});

calling this returns "user created". Here is my method to output all users:

app.get('/users', function(req, res) {

    User.find({}, function(err, user) {
        res.json(user);
    });
});

The output here is

[
  {
    "_id": "565772db5f6f2d1c25e999be",
    "__v": 0
  },
  {
    "_id": "5657734ba859fefc1dca77db",
    "__v": 0
  },
  {
    "_id": "5657738ba859fefc1dca77dc",
    "__v": 0
  },
  {
    "_id": "565774f1cf99a2b81fca1e7f",
    "__v": 0
  },
  {
    "_id": "565775f0cf99a2b81fca1e80",
    "__v": 0
  }
]

Where I've tried to add "Nick" a couple of times noe... any input? :D

My Mongoose model, located in its own Model.js file with other models:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

// set up a mongoose model and pass it using module.exports
module.exports = mongoose.model('User', new Schema({ 
    name: String, 
    password: String, 
}));
Share Improve this question edited Dec 5, 2015 at 14:31 john-jones 7,78019 gold badges55 silver badges88 bronze badges asked Nov 26, 2015 at 21:17 Jason94Jason94 13.6k37 gold badges112 silver badges189 bronze badges 7
  • 1 Change save to .save(function(err,user){ console.log(err)}) to see if there was any error – Molda Commented Nov 26, 2015 at 21:29
  • Where does the User object e from? Are you using mongoose? – tmuecksch Commented Nov 26, 2015 at 21:40
  • No errors and I'm using mongoose yes – Jason94 Commented Nov 26, 2015 at 21:46
  • Then I'd suggest to add the corresponding tag in order to get better answers and not confuse people assuming your script is relying on pure mongo. – tmuecksch Commented Nov 26, 2015 at 21:47
  • 2 I tested your exact set up and everything worked. It was able to save a new user with the name field. I would remend Lisa's set up. – jjbskir Commented Nov 28, 2015 at 23:15
 |  Show 2 more ments

5 Answers 5

Reset to default 5

Given you have a name in you user Schema, you also need to wait until your save() query is finished and then send a response:

app.get('/setup', function (req, res) {
    User.findOne({ name: "Nick" }, function (err, user) {
        if (err) {
          return res.json({ "success": false, "error": err });
        }

        if (user) {
          return res.json({ "success": true, "msg": "user existed" });
        }

        var nick = new User({ name: "Nick" });
        nick.save(function(err, userObj) {
           if (err) {
             return res.json({ "success": false, "error": err });
           }

           res.json({ "success": true, "msg": "user created" });
        });
    });
});

please try with this code :

app.get('/setup', function (req, res) {

    User.findOne({ name: "Nick" }, function (err, user) {

        if (!err && user) {
                res.json({ "success": true, "msg": "user existed" });

        } 
        else {

            var nick = new User({name: "Nick" });
            nick.save(function(err){
               if(!err)
                   res.json({ "success": true, "msg": "user created" });
            })

        }
    });
});

The save() function you have called is incorrect, and follows the pattern of other languages rather than Node.js.

The way Node.js works is totally different from other languages like Java, PHP, Ruby, ASP and etc Javascript is entirely Asynchronous in nature, and Node.js has improved over it as Event-driven and non-blocking I/O. So the code execution doesn't move on unless it has received a response from the function it lies within.

Therefore, after the save() method is executed, it responses back with a callback function sending a pletion response to node.js so it can trigger other executions. The correct code will be

var user = new User({name: 'Nick'});
user.save(function(err, savedUser) {
    if(err) return res.send(err);
    return res.json({'message': 'User created!', user: savedUser});
});

So as you can see, that as soon as the save() method pletes, it responds back the response i.e. err and savedUser in a callback rather than returning them, and every single of the code after the save method will be written inside that callback.

If we take your code for a minute and analyze what the problem is,

var nick = new User({
    name: "Nick",
}).save();

res.json({ "success": true, "msg": "user created" });

when the save() method is called, node.js sends the data along with insert trigger to mongodb, and moves on with the rest of the code execution. And that code is printing "success" even the data is not being saved yet. Therefore almost every method in Node.js has a callback as it's last parameter which sends an indication of pletion.

You need to define name key in your User schema for it be saved.

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var userSchema = new Schema({
  name: String
});

var User = mongoose.model('User', userSchema);

Here is your code and it works. I've only changed the module.exports with var User because of to collect the code in a single page.

So, may be there is another problem?

Good luck...

var express = require('express')
var mongoose = require('mongoose')
var mongoDBUrl = "mongodb://1.0.0.1:27027/tests"

var app = express()

var Schema = mongoose.Schema;
var User = mongoose.model('User', new Schema({ 
    name: String, 
    password: String, 
}));

/* Mongoose Database connection */
mongoose.connect(mongoDBUrl)
var db = mongoose.connection
db.on('error', console.error.bind(console, 'Mongo connection error:'))
db.once('open', function (callback) {
  console.log("MongoDB connection has established")
})

app.get('/setup', function (req, res) {
    User.findOne({ name: "Nick" }, function (err, user) {

        if (user == undefined) {

            var nick = new User({
                name: "Nick",
            }).save();

            res.json({ "success": true, "msg": "user created" });
        } else {
            res.json({ "success": true, "msg": "user existed" });
        }
    });
});

app.get('/users', function(req, res) {
console.log("/user works")

    User.find({}, function(err, user) {
        res.json(user);
    });
});


app.listen(1337, function() {
    console.log('node-app is listening HTTP port 1337')
})

Postman results;

发布评论

评论列表(0)

  1. 暂无评论