简体   繁体   中英

Returning values after save in Mongoose

I'd need some help on returning values after saving a new entry to my db using mongoose.

This is how my controller looks:

var userModel = require('../models/users');

module.exports = {

  findAll: function(req, res) {
    userModel.user.findAll(function(err, users) {
      return res.json(users);
    });
  },

  findId: function(req, res) {
    var id;
    id = req.params.id;
    userModel.user.findId(id, function(err, user) {
      return res.json(user);
    });
  },

  addUser: function(req, res) {
    newUser = new userModel.user;
    newUser.username = req.body.username;
    newUser.password = req.body.password;
    newUser.addUser(function(err, user) {
      return res.json(user);
    });
  }

};

And here's my users.js:

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

var UserSchema = new Schema({
  username: {
    type: String,
    required: true
  },
  password: {
    type: String,
    required: true
  }
});

module.exports = {

  findAll: UserSchema.statics.findAll = function(cb) {
    return this.find(cb);
  },

  findId: UserSchema.statics.findId = function(id, cb) {
    return this.find({
      _id: id
    }, cb);
  },

  addUser: UserSchema.methods.addUser = function(cb) {
    return this.save(cb);
  }

};

This all works ok, but it only returns me the newly added user with addUser. I would like to get all the entries, including the newsly added one, as a return value. Just like using "findAll". How would be able to do this?

Yes, like bernhardw said there doesn't seem to be a way to return anything but the added document with save().

I followed his advice and called findAll() inside addUser() and it all works perfect now -> I can return all my users after saving a new new one. Thanks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM