[英]Pushing data into Mongoose Model array?
Hi i am trying to push string into an array in mongoose. 嗨,我正在尝试将字符串推入猫鼬数组中。 But it is not updating.
但是它没有更新。
My Model is 我的模特是
const userSchema = new mongoose.Schema({
name: {
type: String,
required: true,
minlength: 5,
maxlength: 50
},
email: {
type: String,
required: true,
minlength: 5,
maxlength: 255,
unique: true
},
password: {
type: String,
required: true,
minlength: 5,
maxlength: 1024
},
project:{
type: new mongoose.Schema({
name: {
type: [String], //tryxing to push data here
required: true,
minlength: 2,
maxlength: 50
}
}),
},
isAdmin: Boolean
});
and in the code i am doing 在我正在做的代码中
router.put('/addProject', auth, async (req, res) => { //To update password
user = await User.findByIdAndUpdate(req.user._id,{project:{$push :{name:req.body.projectname}},new :true});
/*********OR********/
User.findOneAndUpdate(
{ _id: req.user._id },
{project:{ $push: { name: req.body.projectname } }},
function (error, success) {
if (error) {
console.log(error);
} else {
console.log(success);
}
});
i tried both the approaches but it is showing me empty array. 我尝试了两种方法,但显示为空数组。 And if there is already data in it get deleted everytime i run this route.. Thanks
而且,如果我每次运行此路线时,其中已经有数据就会被删除。
You need to change the project
and name
fields to: 您需要将
project
和name
字段更改为:
project:{
name: [{
type: String, // and not `type: [String]`
required: true,
minlength: 2,
maxlength: 50
}
}]
},
The final schema would be: 最终方案将是:
// user.model.js
const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({
name: {
type: String,
required: true,
minlength: 5,
maxlength: 50
},
email: {
type: String,
required: true,
minlength: 5,
maxlength: 255,
unique: true
},
password: {
type: String,
required: true,
minlength: 5,
maxlength: 1024
},
project:{
name: [{
type: String,
required: true,
minlength: 2,
maxlength: 50
}]
},
isAdmin: Boolean
});
export default User = mongoose.model('User', userSchema);
Then in your controller: 然后在您的控制器中:
import User from './user.model';
router.put('/addProject', auth, async (req, res) => {
user = await User.findByIdAndUpdate(req.user._id,
{ $push: { 'project.name': req.body.projectname }, { new: true });
...
Edit: To remove an element from the array use $pull : 编辑:要从数组中删除一个元素,请使用$ pull :
await User.findByIdAndUpdate(req.user._id,
{ $pull: { 'project.name': req.body.projectname }, { new: true });
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.