0

I want to find and update only one object in my array of object, that I try to findAndUpdate:

So I want to find my document with correct name and password, and then find only one subdocument, that I want update/save into

logic:

roomModel.findOneAndUpdate({ $and: [{ name: req.body.roomName }, { password: req.body.roomPassword }], 'users.name': req.body.userName }, {
        '$set': {
            'users.$.latitude': req.body.latitude,
            'users.$.longitude': req.body.longitude,
            'users.$.updateDate': new Date()
        }
    })
    .then((room) => {
        // ...
    })

roomModel:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var userSchema = require('./user').userSchema;

var room = new Schema({
    name: String,
    password: String,
    users: [userSchema]
});

module.exports.roomSchema = room;
module.exports.roomModel = mongoose.model('room', room);

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

var user = new Schema({
    name: String,
    latitude: String,
    longitude: String,
    updateTime: Date
});

module.exports.userSchema = user;
module.exports.userModel = mongoose.model('user', user);

I don't exactly know how to perform that and search along with subdocument search

Jakub Pastuszuk
  • 928
  • 4
  • 12
  • 31
  • Actually `{ name: req.body.roomName },password: req.body.roomPassword, 'users.name': req.body.userName }` is exactly the same thing since "all" mongodb query arguments are already "and" expressions by default. You are talking about "projection" using the positional operator `$` to mach the specified document in the array, and you already did that in your argument to `$set`. What's the problem? You "should" shorten the syntax as shown, but the update should still be working. – Neil Lunn May 21 '17 at 23:49
  • Already stated that the update should be working. Are you actually asking *"How do I return with **only** the updated sub-document?"* Just trying to discern the question or at least narrow down what other problem there may be. – Neil Lunn May 21 '17 at 23:58
  • Yeah, it does work, thank for your help – Jakub Pastuszuk May 22 '17 at 00:00
  • 1
    Like I said. the query can be re-written as `{ name: req.body.roomName ,password: req.body.roomPassword, 'users.name': req.body.userName }` (correcting my earlier typo) but as is in your question will actually still work. Just to note though that your statement is mising the correct option to return the "modified" document, if that was your intent. See [Mongoose: findOneAndUpdate doesn't return updated document](http://stackoverflow.com/q/32811510/2313887) – Neil Lunn May 22 '17 at 00:04

0 Answers0