[英]How to save nested mongoDB properties with mongoose?
假設我要創建具有嵌套屬性的用戶架構:
var userSchema = new mongoose.Schema({
username: { type: String, unique: true, lowercase: true },
/* ... some other properties ... */
profile: {
firstName: { type: String, default: '' },
/* ... some other properties ... */
},
});
module.exports = mongoose.model('User', userSchema);
現在,如果我想將用戶保存在像ExpressJs這樣的nodejs框架中,我將像這樣保存它:
var user = new User({
username: req.body.username,
profile.firstName: req.body.firstName /* this is what i want to achive here */
});
user.save(function(err) {
if (!err) {
console.log('User created');
}
});
而且我想知道我的模式是否良好,或者最好是在根目錄中設置所有屬性,如下所示:
var userSchema = new mongoose.Schema({
username: { type: String, unique: true, lowercase: true },
firstName: { type: String },
/* ... some other properties ... */
},
});
模式是好的,但是您不能像在第二個代碼示例中那樣在未引用它們的情況下在新對象的根上定義嵌套屬性。 它看起來應該像這樣:
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test');
var User = mongoose.model('User', {
username: String,
profile: {
firstName: String
}
});
var user1 = new User(
{
username: 'Zildjian',
'profile.firstName':'test'
});
user1.save(function (err) {
if (err) // ...
console.log('meow');
process.exit(0);
});
盡管我建議像這樣正確嵌套
var user1 = new User(
{
username: 'Zildjian',
profile: {
firstName:'test'
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.