我正在尝试添加到MLAB内部的User对象中的现有数组。
我正在使用Mongoose 5.1.1和MongoDB 3.4.9,我觉得我已尝试过update(),findByIdAndUpdate(),findAndModify()等的每一个变体。
我不确定为什么这个update()方法不起作用。当我运行此代码时,我在原始响应中得到{“ok”:0,“n”:0,“nModified”:0}但没有抛出任何错误。我已经阅读了文档,我相信我正在运行这个,但显然没有。
有什么想法?提前谢谢。
MLAB中的User onbject看起来像:
[String(usersActions.updateUser)]: (action, store) => {
return Rx.Observable.fromPromise(
fetch(`${API_ROOT}/user/${get(action, 'payload.id')}`, {
method: 'put',
headers: {},
}).then(res => res.json())
)
.mergeMap(resJson => {
if (resJson['status'] === 200) {
return Rx.Observable.concat(
Rx.Observable.of(
appActions.pushNotification('success', USER_UPDATE_SUCCESS)
),
Rx.Observable.of(
appActions.setNextPath(`/users/${get(action, 'payload.id')}`)
)
)
} else return
Rx.Observable.concat(
Rx.Observable.of(
appActions.pushNotification(
'error',
USER_UPDATE_FAILED + ': ' + resJson['message']
)
)
)
})
.catch(() => {
Rx.Observable.concat(
Rx.Observable.of(
appActions.pushNotification('error', USER_UPDATE_FAILED)
)
)
})
},
我的模特
{
"_id": {
"$oid": "Blah12345"
},
"fbid": "123456789101112",
"email": "myemail@gmail.com",
"name": "My Name",
"__v": 0,
"guestlist": [],
"reviews": []
}
我的api文件
import mongoose from 'mongoose';
import express from 'express';
const router = express.Router();
module.exports = router;
const schemaOptions = {
collection: "users"
};
const Guestlist = new mongoose.Schema({
guestlist: [{
date: String,
name: String,
guys: Number,
girls: Number
}]
}, schemaOptions);
module.exports = mongoose.model('Guestlist', Guestlist);
答案 0 :(得分:1)
无需在此处创建实例...您可以直接使用Guestlist
router.post('/guestlist', (req, res) => {
let date = req.body.date;
let name = req.body.name;
let guys = req.body.guys;
let girls = req.body.girls;
const query = {fbid: req.body.fbid};
const update = { $push: {
guestlist: {
date: date,
name: name,
guys: guys,
girls: girls
}
}};
Guestlist.update(query, update, (err, raw) => {
if (err) throw err;
if (raw) {
console.log(JSON.stringify(raw));
console.log("1 document updated");
res.sendStatus(200);
}
});
})