我第一次使用Mongo而且我在创建一个包含数组的文档时遇到了困难。 该对象传递给nodejs服务器,如下所示:
{
"customerid":"121212",
"name": "Zero 2679",
"email": "a@a.com",
"address": "bla bla bla",
"tokens":[{"ctoken":"123456"},{"ctoken":"1234567"}]
}
代码执行以下操作:
var newCustomer = new Customer(
{
_id: request.body.customerid,
name: request.body.name,
email: request.body.email,
address: request.body.address,
tokens:request.body.tokens
});
newCustomer.save(function (err) {
if (err) winston.log('error', err);
// saved!
})
架构的配置如下:
var customerSchema = new Schema({
// index: true => Tells mongo to index this paramater because it is used frequently. It makes querying faster
_id: {type: String, unique: true}, // unique customer ID
name: {type: String, default: '', required: true}, // Customer name
//email: {type: mongoose.SchemaTypes.Email, required: true},
email: {type: String, required: true},
address: { type: String, required: true },
toknes: [{ ctoken :{type: String} }]
}, {collection: 'customers'});
当我去查看MongoDB中的对象时,它看起来像这样:
{
"_id": "121212",
"email": "a@a.com",
"address": "bla bla bla",
"tokens": [],
"name": "Zero 2679",
"__v": 0
}
令牌丢失,并且有一个'_v'值,我甚至没有。
请告知我做错了什么?
答案 0 :(得分:1)
tokens: [{ ctoken : String }]
request.body.tokens
必须类似= {ctoken: 'some string'}
var newCustomer = new Customer(
{
_id: request.body.customerid,
name: request.body.name,
email: request.body.email,
address: request.body.address,
tokens:[request.body.tokens]
});
newCustomer.save(function (err) {
if (err) winston.log('error', err);
// saved!
})
如果客户数据库文档包含数据,那么您应该执行push
操作
答案 1 :(得分:0)
在您的架构中应该是:
tokens: [{ type: String }]
由于ctoken不是数据类型。工作架构如下所示:
var customerSchema = new Schema({
_id: {type: String, unique: true},
name: {type: String, default: '', required: true},
email: {type: String, required: true},
address: { type: String, required: true },
tokens: [{ type: String }]
}, {collection: 'customers'});