下面的代码包含两个架构现在Grocery Schema包含用户数组,我想在其中存储与itemName相关的所有用户ID 我不知道如何在mongodb中插入新值
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var GrocerySchema= new Schema({
itemName: {
type: String,
required: true,
unique: true
},
completed: Boolean,
date: String,
users:[{user_id:{type:Schema.Types.ObjectId,ref:user}}]
});
grocerydata=mongoose.model('grocery',GrocerySchema);
var UserSchema = new Schema({
fname: {
type:String,
required:true
},
lname:{type:String},
email: {
type: String,
unique: true,
required: true
},
password: {
type: String,
required: true
}
});
module.exports = mongoose.model('User', UserSchema);
我使用下面的代码来保存多个值并设置数组的值
var docs= {
itemName : req.body.item,
completed: true,
date: new Date(),
$push: {"users": {user_id: req.body._id}}
}
}
grocerydata.create(docs, function(err, results) {
if (err)
res.send(err);
console.log(results);
});
但是我无法在grocery中推送user_id请帮助我 在此先感谢!!
答案 0 :(得分:0)
您最后一段代码中有错误。 var docs
应该是以下内容:
var docs={
itemName : req.body.item,
completed: true,
date: new Date(),
//you forgot to wrap $push in {}
{$push: {"users": {user_id: req.body._id}}}
}