在数组猫鼬中插入元素在NodeJS中创建对象

Inserting elements in array mongoose creates Object in NodeJS

我正在尝试使用 Mongoose 在数组中插入文档。

这是架构:

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

NodeJS 中的更新代码如下所示:

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!"}); 
        });
    }
);

但它会插入如下内容:

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

我哪里做错了?再次感谢。

使用 findOneAndUpdate() 方法并将 'upsert' 选项设置为 true - 如果对象不存在(默认为 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!"}); 
});