【发布时间】:2018-05-24 16:33:34
【问题描述】:
我正在尝试将数据推送到我的用户集合文档中的 readBook 数组。 如以下代码和 console.log 返回所示,用户都是从 db 中检索到的,并且有要推送的数据,但是在代码完成工作后没有任何改变。控制台中没有显示错误。请帮忙!
我有一个 mongodb Schema:
const UserSchema = new mongoose.Schema({
_id: Number,
type: {
type: String,
required: true,
default: "personal"
},
email: {
type: String,
unique: true,
required: true,
trim: true
},
username: {
type: String,
unique: true,
required: true,
trim: true
},
name: {
type: String,
required: true,
trim: true
},
password: {
type: String,
required: true,
},
readBook: [{
id: {
type: String,
},
status: {
type: String
},
rating : {
type: String
}
}]
});
并尝试使用 express 向其推送数据:
router.post("/ratebook", (req,res,next) => {
User.findById(1)
.exec( (error, user) => {
if(error) {
return next(error);
} else {
console.log(user);
console.log(req.body);
User.update( { _id: 1}, { $push: {"readBook": req.body}});
}
})
})
console.log 返回:
{ type: 'admin',
readBook: [],
_id: 1,
email: ‘username@gmail.com',
username: 'username',
name: ’Name Surname',
password: '$2a$10$JcuZNrjEh4KNOZ04TxIKLOy4/hcCK0It0.lAAE4zGN/qPavBFx8GS',
__v: 0 }
{ id: '1', bookRating: '4’ }
【问题讨论】:
标签: javascript arrays node.js mongodb express