1

I'm trying to insert documents in an array using Mongoose.

Here's the Schema:

var user = new mongo.Schema({
  _id : Number,
  devices:[
      {
        device_id : String,
        type : String
      }
    ]})

The update code in NodeJS looks like:

app.put('/user/update',function(req,res){
    var obj = req.body;
    users.update(
        {'user.username' : obj.email},
        {
            'user.username' : obj.email, 
            'user.password' : obj.password, 
            'user.name.first' : obj.name, 
            'user.department' : obj.department, 
            'user.year' : obj.year, 
            'user.college' : obj.college,
            'user.contact.phone': obj.contact,  
            'user.last_login' : obj.last_login,
            $push:{ 
                'devices': {
                     device_id: 'sadasd32u4je3bdjas', 
                     type: 'Windows'
                }
            } 
        }, function(err){
                if(err) 
                    res.json({"foo": String(err)});
                else
                    res.json({"foo": "Successfully Signed up!"}); 
        });
    }
);

But instead it inserts something like:

"devices": [
            "[object Object]",
            "[object Object]",
            "[object Object]",
            "[object Object]",
            "[object Object]"
         ],

Where did I go wrong? Thanks again.

1 Answer 1

2

Use the findOneAndUpdate() method with the 'upsert' option set to true - this creates the object if it doesn't exist (defaults to false):

var obj = req.body;
var query = {'user.username': obj.email};
var doc = {
    $set: {
        'user.username': obj.email, 
        'user.password': obj.password, 
        'user.name.first': obj.name, 
        'user.department': obj.department, 
        'user.year': obj.year, 
        'user.college': obj.college,
        'user.contact.phone': obj.contact,  
        'user.last_login': obj.last_login  
    },
    $push: { 
        'devices': {
             device_id: 'sadasd32u4je3bdjas', 
             type: 'Windows'
         }
    }
};
var options = {upsert: true};
users.findOneAndUpdate(query, doc, options, function(err){
    if(err) 
        res.json({"foo": String(err)});
    else
        res.json({"foo": "Successfully Signed up!"}); 
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.