Javascript 将数据推送到mongodb文档中的数组
我正在尝试将数据推送到我的用户集合文档中的readBook数组。 正如代码bellow和console.log return中所示,这两个用户都是从数据库中检索的,并且有数据要推送,但是在代码完成工作后,没有任何更改。控制台中未显示任何错误。请帮忙 我得到了一个mongodb模式:Javascript 将数据推送到mongodb文档中的数组,javascript,arrays,node.js,mongodb,express,Javascript,Arrays,Node.js,Mongodb,Express,我正在尝试将数据推送到我的用户集合文档中的readBook数组。 正如代码bellow和console.log return中所示,这两个用户都是从数据库中检索的,并且有数据要推送,但是在代码完成工作后,没有任何更改。控制台中未显示任何错误。请帮忙 我得到了一个mongodb模式: const UserSchema = new mongoose.Schema({ _id: Number, type: { type: String, required
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’ }
在更新查询上方有console.log位置,如果数据已更新,请在API调用后检查DB 或者使用以下代码并检查console.log
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}}).exec( (errorU, updatedUser) => {
console.log("Update error", errorU);
console.log("Updated User", updatedUser);
});
}
})
})
更新错误null更新用户{n:1,nModified:1,opTime:{ts:Timestamp{bsontype:'Timestamp',低:1,高:1527151320},t:1},electionId:7FFFFFFF0000000001,ok:1}但它仍然不会在db中更新,下次我执行代码时,它仍然保留在空的readBook数组中,您能检查您的req.body中有什么吗?使用控制台可能是{id:'1',bookRating:'4'}是req body。body对象中的键应该与您的架构相同。假设您的req.body应该是{id:1,状态:active,评级:4}