我试图使用Mongoose在数组中插入文档。
这是Schema:
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]"
],
我哪里出错了?再次感谢。
答案 0 :(得分:2)
将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!"});
});